package com.das.mechanic_alone.mvp.view.alone;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.das.mechanic_alone.R;
import com.das.mechanic_alone.mvp.contract.alone.X3AloneContract;
import com.das.mechanic_alone.mvp.presenter.alone.X3AlonePresenter;
import com.das.mechanic_alone.mvp.view.alone.utils.AloneHotCommentHelper;
import com.das.mechanic_alone.mvp.view.alone.utils.X3AloneChangePagerUtils;
import com.das.mechanic_alone.widget.X3BottomAloneAnswerDialog;
import com.das.mechanic_alone.widget.X3BottomAloneStatusDialog;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.adapter.alone.X3AloneChoiceAdapter;
import com.das.mechanic_base.adapter.alone.X3CameraNewAdapter;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.bean.alone.AloneCarBean;
import com.das.mechanic_base.bean.alone.AloneChoiceBean;
import com.das.mechanic_base.bean.alone.AloneDeductionBean;
import com.das.mechanic_base.bean.alone.AloneHideBean;
import com.das.mechanic_base.bean.alone.AloneImageAndRecordBean;
import com.das.mechanic_base.bean.alone.AloneImageBean;
import com.das.mechanic_base.bean.alone.AloneItemCommentBean;
import com.das.mechanic_base.bean.alone.AloneNewBean;
import com.das.mechanic_base.bean.alone.EditInputBean;
import com.das.mechanic_base.bean.alone.SpeechBean;
import com.das.mechanic_base.bean.alone.TestRecommendBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.common.AwsFileBean;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.bean.main.HomeMainCarBean;
import com.das.mechanic_base.def.alone.AloneContainerStatusDef;
import com.das.mechanic_base.def.alone.AloneSubmitStatus;
import com.das.mechanic_base.def.alone.AloneUploadStatus;
import com.das.mechanic_base.gen.DaoSessionUtils;
import com.das.mechanic_base.utils.AverageGapItemDecoration;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.SoftKeyBoardListener;
import com.das.mechanic_base.utils.SoftKeyboardStateHelper;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3AloneLayoutUtils;
import com.das.mechanic_base.utils.X3AloneServiceSearchUtils;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3EdittextWatcher;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.das.mechanic_base.widget.X3AlonePassDialog;
import com.das.mechanic_base.widget.X3AloneSoundView;
import com.das.mechanic_base.widget.X3BottomAffirmMileDialog;
import com.das.mechanic_base.widget.X3BottomAlreadyAloneServiceDialog;
import com.das.mechanic_base.widget.X3MarqueeText;
import com.das.mechanic_base.widget.X3MemberButtonView;
import com.das.mechanic_base.widget.X3MyRecyclerview;
import com.das.mechanic_base.widget.X3NewBottomMileOrTimeDialog;
import com.das.mechanic_base.widget.X3RecommendForYouPopWindow;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.umeng.analytics.MobclickAgent;
import com.zhpan.indicator.IndicatorView;
import com.zhpan.indicator.enums.IndicatorSlideMode;
import com.zhpan.indicator.enums.IndicatorStyle;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by chenSi on 2018/3/13.
 */
@Route(path = X3AppRouterConstants.Router.ALONE_INFO)
public class X3AloneActivity extends X3BaseActivity<X3AlonePresenter> implements X3AloneContract.View, X3AloneLayoutUtils.IOnAloneClick, X3CameraNewAdapter.IOnItemCameraClick, X3BottomAloneStatusDialog.IOnClickJump, X3MemberButtonView.IOnClickAffirm, X3AlonePassDialog.IBtnClick, View.OnFocusChangeListener {

    @BindView(R2.id.tv_title)
    X3MarqueeText tv_title;
    @BindView(R2.id.btn_submit)
    X3MemberButtonView btn_submit;
    @BindView(R2.id.tv_mask_commit)
    TextView tv_mask_commit;
    @BindView(R2.id.al_container)
    LinearLayout al_container;
    @BindView(R2.id.sl_content)
    ScrollView sl_content;
    @BindView(R2.id.rl_header)
    RelativeLayout rl_header;
    @BindView(R2.id.tv_service_num)
    TextView tv_service_num;
    @BindView(R2.id.v_tips)
    View v_tips;
    @BindView(R2.id.tv_num)
    TextView tv_num;
    @BindView(R2.id.ll_bottom)
    LinearLayout ll_bottom;

    @BindView(R2.id.v_bottom_holder)
    View v_bottom_holder;

    @BindView(R2.id.fl_parent)
    FrameLayout fl_parent;

    @BindView(R2.id.ll_start)
    LinearLayout ll_start;
    @BindView(R2.id.as_view)
    X3AloneSoundView as_view;
    @BindView(R2.id.tv_end)
    TextView tv_end;
    @BindView(R2.id.rl_voice_content)
    RelativeLayout rl_voice_content;


    private HashMap<Long, AloneCarBean> cameraAllList;

    // 上传评论的录音
    private int evaluaNum = 0;

    private int evaluaAlreadyNum = 0;

    /**
     * 存储前后轮胎尺寸的状态view
     */
    private List<View> tyreViews;

    // 存储edittext输入的文字
//    private EditInputBean inputBean;

    private List<AloneNewBean.ItemQuestionListBean> aloneNewBeans;

    // 控制是否点击了title 是否要显示对应的布局
    private List<AloneHideBean> hideBeans;

    /**
     * 存储每一个检测点的答题状况
     */
    private List<List<Boolean>> isSave;

    /**
     * 存储每一个检测点的view
     */
    private HashMap<Integer,List<LinearLayout>> pointMap = new HashMap<>();

    /**
     * 存储每一个检测点的shape
     */
    private HashMap<Integer,HashMap<Integer,View>> shapeMap = new HashMap<>();

    /**
     * 存储每一个检测点对应的推荐服务项目的父布局
     */
    private HashMap<Long,View> recommendMap = new HashMap<>();

    /**
     * 存储每一个选择题的数据
     */
    private HashMap<Integer,HashMap<Integer,AloneChoiceBean>> choiceMap = new HashMap<>();

    /**
     * 存储每一个检测点的状态
     */
    private List<List<String>> isStatus;

    /**
     * 存储每一个检测点评论的输入框,用来判断当前是哪个editext正在获得焦点，并且可以把技师常用评论赋值到这个view上，
     */
    private List<EditText> commentEditextList = new ArrayList<>();

    private HashMap<String,EditText> commentMap = new HashMap<String,EditText>();

    private String filePath;

    private boolean isSubmit;

    private List<List<String>> contentList = new ArrayList<>();

    private List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> aloneBeans;

    /**
     * 存储当前拍照 是在那个检测项 检测点
     */
    private long titleIndex = 0L;
    private List<String> contents;
    private Gson gson;
    private SpeechRecognizer mIat;
    private String evaluaFile;
    private long evaluaId = 0;
    private X3AloneLayoutUtils layoutUtils;
    private double currentMiles;
    private double perMiles;

    private X3BottomAlreadyAloneServiceDialog alreadyAloneServiceDialog;

    private String evaluation;
    /**
     * 0 需要审核
     * 1 不需要审核
     */
    private int reportStatus;
    private X3BottomAloneAnswerDialog answerDialog;
    private X3BottomAloneStatusDialog statusDialog;
    private X3AlonePassDialog passDialog;
    private boolean isAll;
    private List<AloneNewBean.ItemQuestionListBean> passAloneBean;
    private List<AloneServiceListBean> serviceList;
    private long allNum,aleadyAnswerNum;
    private String mgtCreate;
    private boolean needUpdateMile;
    private HomeMainCarBean carBean;
    private AloneServiceListBean aloneServiceListBean;
    private String km,inputAnswer;
    private long jumpIndex;
    private X3BottomAffirmMileDialog mileDialog;

    /**
     * 检测项的拍照是在答题前还是在答题后，ture 在前，false 在后
     */
    private boolean aloneItemPicOrder = false;

    /**
     * 检测点获得焦点的输入框
     */
    private EditText currentFocusEt;

    /**
     * 检测点的录音文件地址
     */
    private HashMap<String,String> itemVoiceFileMap = new HashMap<>();

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.x3_alone_container_fragment;
    }

    @Override
    public boolean isTransparent() {
        return true;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        cameraOrder();


        X3StatusBarUtil.darkMode(this);
        km = (String) SpHelper.getData(X3Constent.MILEAGEUNIT, "km");
        mgtCreate = getIntent().getStringExtra("mgtCreate");
        jumpIndex = getIntent().getLongExtra("jumpIndex", -1L);
        layoutUtils = new X3AloneLayoutUtils(this);
        layoutUtils.setiOnAloneClick(this);
        gson = new Gson();
        cameraAllList = new HashMap<>();
        aloneBeans = new ArrayList<>();
        hideBeans = new ArrayList<>();
        tyreViews = new ArrayList<>();

        carBean = (HomeMainCarBean) getIntent().getSerializableExtra("carBean");

        needUpdateMile = getIntent().getBooleanExtra("needUpdateMile", false);

        reportStatus = getIntent().getIntExtra("reportStatus", 0);

        filePath = X3FileUtils.getStoragePath(this, X3FileUtils.ALONE_STORAGE_PATH);

        isSubmit = getIntent().getBooleanExtra("isSubmit", false);

        btn_submit.changeText(isSubmit ? getString(R.string.x3_alone_again_submit) : getString(R.string.x3_btn_submit));
        btn_submit.setiOnClickAffirm(this);

        tv_mask_commit.setText(isSubmit ? getString(R.string.x3_alone_again_submit) : getString(R.string.x3_btn_submit));


        // 设置标题
        tv_title.setText(getIntent().getStringExtra("title") + "");

        tv_title.setOnClickListener(new DoubleClickListener(){
            @Override
            public void onDoubleClick(View v) {
                sl_content.post(() -> sl_content.fullScroll(View.FOCUS_UP));
            }
        });

        if(mPresenter != null) {
            mPresenter.start();
        }

        keyBoardParams();

//        keyBoardParams2();

//        keyBoardHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                v_bottom_holder.setVisibility(View.GONE);
//            }
//        },1500);

    }

    private void cameraOrder(){
        String mobile = (String) SpHelper.getData("mobile", "");
        aloneItemPicOrder = (boolean) SpHelper.getData(mobile + X3Constent.ALONE_CAMERA_ORDER  , true);
        Log.e("camera_order","aloneItemPicOrder = " + aloneItemPicOrder);
        Log.e("camera_order","mobile() = " + mobile);
        Log.e("camera_order","providerWorkBaseId() = " + providerWorkBaseId());
    }

    @Override
    public void showCurrenMiles(double currentMiles, double perMiles) {
        this.currentMiles = currentMiles;
        this.perMiles = perMiles;
    }

    /**
     * 削减滑竿题 + 选择题
     * @param titleIndex
     */
    private void cuteSliderAlone(long titleIndex,long contentIndex,String content,
                                 String desTitle,AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean beforeList,
                                 AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean afterList) {

        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> questionList = aloneNewBeans.get((int) titleIndex).questionDetectionTempletQuestionList;
        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> deductionList = questionList.get((int) contentIndex).questionCarMilesDeductionEntityList;

        long questionBaseId = questionList.get((int) contentIndex).questionBaseId;
        String type = questionList.get((int) contentIndex).type;

        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean.TouchCycleBaseServiceEntityListBean> beforeTouchList = beforeList.touchCycleBaseServiceEntityList;
        if (X3StringUtils.isListEmpty(beforeTouchList)) {
            beforeTouchList = new ArrayList<>();
        }
        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean.TouchCycleBaseServiceEntityListBean> afterTouchList = afterList.touchCycleBaseServiceEntityList;
        if (X3StringUtils.isListEmpty(afterTouchList)) {
            afterTouchList = new ArrayList<>();
        }

        switch (type) {
            case AloneContainerStatusDef.CHOICE:
                if (X3StringUtils.isEmpty(content)) {
                    content = "";
                }
                AloneDeductionBean choiceBean = X3AloneChangePagerUtils.getCurrentChoiceStatus(content, deductionList);


                removeSelectService(beforeTouchList,questionBaseId);
                addSelectService(afterTouchList,questionBaseId,desTitle,choiceBean.id);

                break;
            case AloneContainerStatusDef.NUMBER:
                double numberAnswer = -1;
                if (!X3StringUtils.isEmpty(content) && X3StringUtils.isAloneNum(content)) {
                    numberAnswer = Double.parseDouble(content);
                }
                AloneDeductionBean numberBean = X3AloneChangePagerUtils.getCurrentNumberStatus(numberAnswer, deductionList);

                removeSelectService(beforeTouchList,questionBaseId);
                // 选择异常的选项 那么要将系统推荐服务项目 添加
                addSelectService(afterTouchList,questionBaseId,desTitle,numberBean.id);

                break;
            case AloneContainerStatusDef.PERCENT_SLIDER:
                double percentAnswer = -1;
                if (!X3StringUtils.isEmpty(content) && X3StringUtils.isAloneNum(content)) {
                    percentAnswer = Double.parseDouble(content);
                }
                AloneDeductionBean percentBean = X3AloneChangePagerUtils.getPercentNumberStatus(percentAnswer, deductionList);

                removeSelectService(beforeTouchList,questionBaseId);
                // 选择异常的选项 那么要将系统推荐服务项目 添加
                addSelectService(afterTouchList,questionBaseId,desTitle,percentBean.id);

                break;
            case AloneContainerStatusDef.TYRE_CHOICE:
                /**
                 * TODO 前后轮胎尺寸削减
                 */
                break;
        }

        drawAllCheckView(false);
    }

    /**
     * 更新所有的添加推荐服务项目的地方
     * isAlreadySave 是否已经修改过了
     * @param
     */
    private void drawAllCheckView(boolean isAlreadySave) {
        if (recommendMap == null) {
            return;
        }
        for (int i = 0; i < aloneNewBeans.size(); i++) {

            List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> itemList = aloneNewBeans.get(i).questionDetectionTempletQuestionList;

            if (X3StringUtils.isListEmpty(itemList)) {
                continue;
            }

            for (int j = 0; j < itemList.size(); j++) {
                long questionBaseId = itemList.get(j).questionBaseId;
                drawCheckService(getAloneServiceBeanByQuestionId(questionBaseId),questionBaseId);
            }
        }
        if (mPresenter != null && !isAlreadySave) {
            mPresenter.saveDetectionService(serviceList);
        }
    }

    /**
     * 选择了非正常的答案 所有要将系统推荐的服务添加到缓存的购物车当中
     * @param touchList
     * @param questionBaseId
     * @param optionId 答案id
     */
    private void addSelectService(List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean.TouchCycleBaseServiceEntityListBean> touchList,
                                  long questionBaseId,String decTitle,long optionId) {
        if (X3StringUtils.isListEmpty(touchList)) {
            return;
        }
        for (int touchIndex = 0; touchIndex < touchList.size(); touchIndex++) {
            AloneServiceListBean serviceListBean = X3AloneServiceSearchUtils.searchAloneServiceBean(serviceList,touchList.get(touchIndex).serviceBaseSn);
            AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean.TouchCycleBaseServiceEntityListBean touchCycleBean = touchList.get(touchIndex);

            List<Long> idList = new ArrayList<>();
            List<String> titleList = new ArrayList<>();

            if (serviceListBean == null) {
                serviceListBean = new AloneServiceListBean();
                serviceListBean.setWorkBaseId(providerWorkBaseId());
                serviceListBean.setTouchServiceBaseName(touchCycleBean.serviceBaseName);
                serviceListBean.setTouchServiceSn(touchCycleBean.serviceBaseSn);
                serviceListBean.setCurrentMiles(currentMiles);
                serviceListBean.setPerMiles(perMiles);
                serviceListBean.setReductionType(touchCycleBean.reductionType);

                if (!idList.contains(questionBaseId)) {
                    idList.add(questionBaseId);
                }
                serviceListBean.setTouchQuestionBaseIdList(idList);

                titleList.add(decTitle);
                serviceListBean.setTouchQuestionBaseDescriptionList(titleList);

                List<AloneServiceListBean.IdBean> idBeans = new ArrayList<>();
                idBeans.add(new AloneServiceListBean.IdBean(questionBaseId,optionId));
                serviceListBean.setQuestionAndOptionIdVOList(idBeans);

                if ("MILE".equals(touchCycleBean.reductionType)) {
                    serviceListBean.setRecommendSafeMiles(currentMiles + touchCycleBean.amount);
                }else {
                    String warnDate = X3DateUtils.addMonth(new Date(System.currentTimeMillis()), (int) touchCycleBean.amount);
                    serviceListBean.setWarningDate(warnDate);

                }
                serviceList.add(serviceListBean);
            }else {
                serviceListBean.setReductionType(touchCycleBean.reductionType);

                titleList = serviceListBean.getTouchQuestionBaseDescriptionList();

                if (X3StringUtils.isListEmpty(titleList)) {
                    titleList = new ArrayList<>();
                }
                if (!titleList.contains(decTitle)) {
                    titleList.add(decTitle);
                }

                if ("MILE".equals(touchCycleBean.reductionType)) {
                    serviceListBean.setRecommendSafeMiles(currentMiles + touchCycleBean.amount);
                }else {
                    String warnDate = X3DateUtils.addMonth(new Date(System.currentTimeMillis()), (int) touchCycleBean.amount);
                    serviceListBean.setWarningDate(warnDate);

                }
                List<AloneServiceListBean.IdBean> idBeans = serviceListBean.getQuestionAndOptionIdVOList();
                if (X3StringUtils.isListEmpty(idBeans)) {
                    idBeans = new ArrayList<>();
                }
                idBeans.add(new AloneServiceListBean.IdBean(questionBaseId,optionId));
                serviceListBean.setQuestionAndOptionIdVOList(idBeans);
                idList.add(questionBaseId);

                serviceListBean.setCurrentMiles(currentMiles);
                serviceListBean.setPerMiles(perMiles);
                serviceListBean.setTouchQuestionBaseDescriptionList(titleList);
                serviceListBean.setTouchQuestionBaseIdList(idList);

                serviceList = X3AloneServiceSearchUtils.replaceAloneServiceBean(serviceList,touchList.get(touchIndex).serviceBaseSn,serviceListBean);
            }
        }
    }

    /**
     * 选择正常的答案 要把系统推荐的服务去除
     * @param touchList
     * @param questionBaseId
     */
    private void removeSelectService(List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean.TouchCycleBaseServiceEntityListBean> touchList
            , long questionBaseId) {
        if (X3StringUtils.isListEmpty(touchList)) {
            return;
        }

        for (int touchIndex = 0; touchIndex < touchList.size(); touchIndex++) {
            AloneServiceListBean serviceListBean = X3AloneServiceSearchUtils.searchAloneServiceBean(serviceList,touchList.get(touchIndex).serviceBaseSn);
            if (serviceListBean == null) {
                continue;
            }

            List<AloneServiceListBean.IdBean> idList = serviceListBean.getQuestionAndOptionIdVOList();
            if (X3StringUtils.isListEmpty(idList)) {
                continue;
            }

            Iterator<AloneServiceListBean.IdBean> iterator = idList.iterator();
            while (iterator.hasNext()) {
                AloneServiceListBean.IdBean next = iterator.next();
                if (next.getQuestionBaseId() == questionBaseId && next.getOptionsId() != 0) {
                    iterator.remove();
                }
            }

            if (X3StringUtils.isListEmpty(idList)) {
                serviceList = X3AloneServiceSearchUtils.deleteAloneServiceBean(serviceList,serviceListBean.getTouchServiceSn());
                continue;
            }

            List<Long> touchIdList = serviceListBean.getTouchQuestionBaseIdList();

            if (!X3StringUtils.isListEmpty(touchIdList) && touchIdList.contains(questionBaseId)) {
                HashSet<Long> set = new HashSet<>(touchIdList);
                set.remove(questionBaseId);
                touchIdList = new ArrayList<>(set);
            }
            serviceListBean.setTouchQuestionBaseIdList(touchIdList);
            serviceListBean.setQuestionAndOptionIdVOList(idList);
            serviceList = X3AloneServiceSearchUtils.replaceAloneServiceBean(serviceList,touchList.get(touchIndex).serviceBaseSn,serviceListBean);
        }
    }

    @Override
    protected X3AlonePresenter createPresenter() {
        return new X3AlonePresenter();
    }

    @OnClick({R2.id.iv_back,R2.id.iv_service_car,R2.id.rl_num,R2.id.iv_pass,R2.id.rl_shop_car,R2.id.tv_mask_commit,R2.id.rl_voice_content})
    public void onViewClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            back();
        } else if (id == R.id.iv_service_car || id == R.id.rl_shop_car) {
            /**
         * 展示购物车
         */
            showAlreadyAloneDialog();
        } else if (id == R.id.rl_num) {
            if (statusDialog != null) {
                statusDialog.show();
                statusDialog.changeData(isStatus, aloneNewBeans,contentList, (int)allNum, (int)aleadyAnswerNum, btn_submit.getTextContent(), btn_submit.getStatus());
                statusDialog.setiOnClickJump(this);
            }
        } else if (id == R.id.iv_pass) {/**
         *TODO 点击全部通过
         */
            showPassDialog(aloneNewBeans, true);
        } else if (id == R.id.tv_mask_commit){
            // 滚动到第一个没有做的题目
            scrollToUnAnswer();
        } else if (id == R.id.rl_voice_content){
            stopListening();
        }
    }

    /**
     * 调整到未答题的item
     */
    private void scrollToUnAnswer(){
        boolean stop = false;
        for (int i=0;i<isStatus.size();i++){
            if (!stop){
                List<String> subList  = isStatus.get(i);
                for (int j=0;j<subList.size();j++){
                    if (X3StringUtils.isEmpty(subList.get(j))){
                        iOnClickJumpToIndex(i,j);
                        stop = true;
                        break;
                    }
                }
            }
        }
    }

    /**
     * 计算有多少道题目需要手动设置
     * isAll 是否所有检测项全部提交成pass
     * 另外一种情况是单个检测项下的所有检测点
     */
    private void showPassDialog(List<AloneNewBean.ItemQuestionListBean> aloneNewBeans,boolean isAll) {
        this.isAll = isAll;
        this.passAloneBean = aloneNewBeans;
        if (X3StringUtils.isListEmpty(aloneNewBeans)) {
            return;
        }
        List<String> showNoPassList = new ArrayList<>();
        int passNum = 0;
        for (int i = 0; i < aloneNewBeans.size(); i++) {
            List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> aloneBeans = aloneNewBeans.get(i).questionDetectionTempletQuestionList;
            for (int j = 0; j < aloneBeans.size(); j++) {
                String type = aloneBeans.get(j).type;
                String description = aloneBeans.get(j).description;
                List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> carList = aloneBeans.get(j).questionCarMilesDeductionEntityList;
                switch (type) {
                    case AloneContainerStatusDef.CHOICE:
                        int isCanPass = 0;
                        if (X3StringUtils.isListEmpty(carList)) {
                            showNoPassList.add(description);
                            continue;
                        }
                        int num = 0;
                        for (int passIndex = 0; passIndex < carList.size(); passIndex++) {
                            String status = carList.get(passIndex).status;
                            if (AloneSubmitStatus.PASS.equals(status)) {
                                isCanPass++;
                            }
                        }
                        if (isCanPass == 1) {
                            passNum++;
                        }else {
                            showNoPassList.add(description);
                        }

                        break;
                    case AloneContainerStatusDef.PERCENT_SLIDER:
                    case AloneContainerStatusDef.NUMBER:
                        showNoPassList.add(description);
                        break;
                    default:
                        break;
                }
            }
        }

        if (passDialog == null) {
            passDialog = new X3AlonePassDialog(this);
        }
        passDialog.show();
        if (passNum > 0) {
            if (X3StringUtils.isListEmpty(showNoPassList)) {
                passDialog.changePassDialog(getString(R.string.x3_all_pass),String.format(passNum == 1 ? getString(R.string.x3_pass_num_answer) : getString(R.string.x3_pass_num_answers),passNum),false);
            }else {
                String content = "";
                for (int i = 0; i < showNoPassList.size(); i++) {
                    if (i == 0) {
                        content = showNoPassList.get(i);
                    }else {
                        content = content + "," + showNoPassList.get(i);
                    }
                }
                passDialog.changePassDialog(getString(R.string.x3_all_pass),String.format(getString(R.string.x3_pass_num_input),passNum,content),false);
            }
        }else {
            passDialog.changePassDialog(getString(R.string.x3_no_all_pass),getString(R.string.x3_input_pass),true);
        }
        passDialog.setiBtnClick(this);

    }

    private void showAlreadyAloneDialog() {
        alreadyAloneServiceDialog = new X3BottomAlreadyAloneServiceDialog(this);
        alreadyAloneServiceDialog.show();
        alreadyAloneServiceDialog.getCurrentDetectionList(providerWorkBaseId(),needUpdateMile,carBean);
    }

    /**
     * 添加推荐服务的弹窗
     */
    private void showAloneDialog(long questionBaseId, long titleIndex, String decTitle, long questionOptionId, List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> deductionList) {
        this.titleIndex = titleIndex;
        Bundle bundle = new Bundle();
        bundle.putLong("workBaseId",providerWorkBaseId());
        bundle.putLong("questionBaseId", questionBaseId);
        bundle.putString("decTitle", decTitle);
        bundle.putLong("carId",getIntent().getLongExtra("carId",0L));
        bundle.putBoolean("needUpdateMile",needUpdateMile);
        bundle.putLong("questionOptionId",questionOptionId);
        bundle.putDouble("currentMiles",currentMiles);
        bundle.putDouble("perMiles",perMiles);
        bundle.putSerializable("carBean",carBean);
        bundle.putSerializable("deductionList", (Serializable) deductionList);
        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.NEW_ALONE_SERVICE,bundle);

//        Intent intent = new Intent(this, com.das.mechanic_main.mvp.view.alone.NewAloneServiceActivity.class);
//        intent.putExtra("workBaseId",providerWorkBaseId());
//        intent.putExtra("questionBaseId", questionBaseId);
//        intent.putExtra("decTitle", decTitle);
//        intent.putExtra("carId",getIntent().getIntExtra("carId",0));
//        intent.putExtra("needUpdateMile",needUpdateMile);
//        intent.putExtra("questionOptionId",questionOptionId);
//        intent.putExtra("currentMiles",currentMiles);
//        intent.putExtra("perMiles",perMiles);
//        intent.putExtra("carBean",carBean);
//        intent.putExtra("deductionList", (Serializable) deductionList);
//        startActivity(intent);
//        overridePendingTransition(R.anim.activity_enter, 0);
    }

    @Override
    public List<AloneNewBean.ItemQuestionListBean> providerAloneNewBeans() {
        return aloneNewBeans;
    }

    @Override
    public long providerToSystemId() {
        return getIntent().getLongExtra("toSystemId",0L);
    }

    @Override
    public String providerContent() {
//        return inputBean != null ? inputBean.getContent() + "" : "";
        return  "";
    }

    @Override
    public long providerToSystem() {
        return this.getIntent().getLongExtra("toSystem",0L);
    }

    @Override
    public long providerWorkBaseId() {
        return getIntent().getLongExtra("workBaseId", 0L);
    }

    @Override
    public void back() {
        finish();
        overridePendingTransition(0, R.anim.activity_exit);
    }

    /**
     * 用来显示有几个检测点没有完成
     */
    protected void showAleadyAnswerNum(List<AloneNewBean.ItemQuestionListBean> aloneNewBeans) {
        if (X3StringUtils.isListEmpty(isSave)) {
            return;
        }

        if (statusDialog == null) {
            statusDialog = new X3BottomAloneStatusDialog(this);
        }

        allNum = 0;
        aleadyAnswerNum = 0;
        isStatus = new ArrayList<>();

        boolean isRed = false;
        for (int i = 0; i < isSave.size(); i++) {
            Log.d("selected_status","设置答题完成状态前 = i = " + i + " isSave.size() = " + isSave.size());

            List<Boolean> mList = isSave.get(i);
            List<String> cList = contentList.get(i);
            List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> qList = aloneNewBeans.get(i).questionDetectionTempletQuestionList;
            if (X3StringUtils.isListEmpty(mList)) {
                isStatus.add(i,new ArrayList<>());
                continue;
            }

            List<String> isStatusOne = new ArrayList<>();
            for (int j = 0; j < mList.size(); j++) {
                Log.i("selected_status","设置答题完成状态前 = j = " + j +" size= " + (mList.size()) );

                if (qList.size()<=j){
                    Log.e("selected_status","数据不匹配直接跳出 qList.size()<=j qList.size() = " + qList.size() + " j= " + j);

                    break;
                }
                Boolean isAnswer = mList.get(j);
                allNum++;
                Log.e("selected_status","总题数量 " + allNum);
                if (!isAnswer) {
                    isStatusOne.add(j,"");
                    continue;
                }
                aleadyAnswerNum++;
                Log.e("selected_status","已答题数量 " + aleadyAnswerNum);

                List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> carList = qList.get(j).questionCarMilesDeductionEntityList;
                String questionBaseStatus = "";
                String answer = cList.get(j);
                switch (qList.get(j).type) {
                    case AloneContainerStatusDef.CHOICE:
                        questionBaseStatus = X3AloneChangePagerUtils.getCurrentChoiceStatus(answer, carList).status;
                        if (X3StringUtils.isEmpty(answer)) {
                            isRed = true;
                        }else {
                            if (!answer.equals(qList.get(j).answer)) {
                                isRed = true;
                            }
                        }

                        break;
                    case AloneContainerStatusDef.PERCENT_SLIDER:
                        if (!X3StringUtils.isEmpty(answer) && X3StringUtils.isAloneNum(answer)) {
                            questionBaseStatus = X3AloneChangePagerUtils.getPercentNumberStatus(Double.parseDouble(answer), carList).status;
                            if (!answer.equals(qList.get(j).answer)) {
                                isRed = true;
                            }
                        }

                        break;
                    case AloneContainerStatusDef.NUMBER:
                        if (!X3StringUtils.isEmpty(answer) && X3StringUtils.isAloneNum(answer)) {
                            questionBaseStatus = X3AloneChangePagerUtils.getCurrentNumberStatus(Double.parseDouble(answer), carList).status;
                            if (!answer.equals(qList.get(j).answer)) {
                                isRed = true;
                            }
                        }
                        break;
                    default:
                        questionBaseStatus = "";
                        break;
                }
                isStatusOne.add(j,questionBaseStatus);
            }
            isStatus.add(i,isStatusOne);
        }

        SpHelper.saveData(providerWorkBaseId() + providerToSystem() + "ISRED",isRed);

        String aleady = aleadyAnswerNum + "";
        String all = "/" + allNum;

        SpannableString numSpan = new SpannableString(aleady + all);
        numSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#0077ff")), 0, aleady.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        numSpan.setSpan(new RelativeSizeSpan(1.0f), aleady.length(), aleady.length() + all.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        numSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#313340")), aleady.length(), aleady.length() + all.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        Log.e("selected_status","综合数量 " + aleady + all);

        tv_num.setText(numSpan);
    }

    /**
     * 生成检测项目和检测点的布局
     * @param aloneNetBeans
     * @param isCreate
     */
    @Override
    public void switchAloneSystem(List<AloneNewBean.ItemQuestionListBean> aloneNetBeans,boolean isCreate) {
        isSave = new ArrayList<>();
        isStatus = new ArrayList<>();
        this.aloneNewBeans = aloneNetBeans;
        hideBeans.clear();
        shapeMap = new HashMap<>();
        choiceMap.clear();

        al_container.removeAllViews();
        //
        contentList.clear();
        cameraAllList.clear();
        tyreViews.clear();
        pointMap.clear();
        recommendMap.clear();
        commentEditextList.clear();
        for (int j = 0; j < aloneNewBeans.size(); j++) {
            aloneBeans = aloneNewBeans.get(j).questionDetectionTempletQuestionList;

            /**
             * 创建检测项title
             */
            int num = 0;
            if (!X3StringUtils.isListEmpty(aloneBeans)) {
                num = aloneBeans.size();
            }
            String point_check = (num == 1) ? String.format(getString(R.string.x3_main_tain_num), num) : String.format(getString(R.string.x3_main_tain_nums), num);
            View titleView = layoutUtils.getParentTitleView(j, aloneNewBeans.get(j).toItemDesc);
            al_container.addView(titleView);
            TextView tv_point = titleView.findViewById(R.id.tv_point);
//            TextView tv_pass = titleView.findViewById(R.id.tv_pass);
            TextView studyView = titleView.findViewById(R.id.tv_study);
            View v_divider_top_title = titleView.findViewById(R.id.v_divider_top_title);
            tv_point.setText(point_check + "");

            // 检测点标记通过
            int finalJ3 = j;
//            tv_pass.setOnClickListener(view -> {
//                List<AloneNewBean.ItemQuestionListBean> passBean = new ArrayList<>();
//                passBean.add(aloneNewBeans.get(finalJ3));
//                showPassDialog(passBean,false);
//            });

//            TextView studyView = new TextView(this);
//            LinearLayout.LayoutParams studyLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//            studyLayout.leftMargin = X3ScreenUtils.dipToPx(12,this);
//            studyView.setPadding(X3ScreenUtils.dipToPx(10,this), X3ScreenUtils.dipToPx(10,this), X3ScreenUtils.dipToPx(10,this), X3ScreenUtils.dipToPx(10,this));
//            studyView.setLayoutParams(studyLayout);
//            al_container.addView(studyView);
//
            Drawable drawable = ContextCompat.getDrawable(this,R.mipmap.x3_alone_sample_icon);
            drawable.setBounds(X3ScreenUtils.dipToPx(5,this), 0, drawable.getMinimumWidth() + X3ScreenUtils.dipToPx(5,this), drawable.getMinimumHeight());
//            studyView.setCompoundDrawables(null, null, drawable, null);
//            studyView.setText(getString(R.string.x3_alone_sample));
//            studyView.setTextColor(ContextCompat.getColor(this,R.color.c0077ff));

            String normalVideoUrl = aloneNewBeans.get(j).normalVideoUrl;
            if (X3StringUtils.isEmpty(normalVideoUrl)) {
                studyView.setVisibility(View.GONE);
                v_divider_top_title.setVisibility(View.GONE);
            }

            /**
             * 跳转到检测实例 视频
             */
            studyView.setOnClickListener(v -> {
                List<String> mList = new ArrayList<>();
                mList.add(normalVideoUrl);
                X3Utils.startShowImage(X3AloneActivity.this,mList,0);
            });

            /**
             * 检测项的拍照布局
             */
            if (aloneItemPicOrder){
                addCameraView(j,isCreate);
            }

            /**
             * 创建点击title之后 可以隐藏的主体内容
             */
            LinearLayout lv_content = layoutUtils.getParentLinearLayout();

            HashMap<Integer,AloneChoiceBean> choice_Lists = new HashMap<>();

            List<Boolean> isSaveOne = new ArrayList<>();
            List<String> isStatusOne = new ArrayList<>();
            contents = new ArrayList<>();
            HashMap<Integer,View> shapeSonMap = new HashMap<>();
            List<LinearLayout> pointList = new ArrayList<>();
            for (int i = 0; i < aloneBeans.size(); i++) {
                LinearLayout pointLayout = layoutUtils.getPointLinearLayout();
                pointList.add(pointLayout);

                String description = aloneBeans.get(i).description;
                long optionsId = aloneBeans.get(i).id;
                long questionBaseId = aloneBeans.get(i).questionBaseId;
                Log.e("alone_id","questionBaseId = " + questionBaseId);
                // 这个是检测点
                View sonTitle = View.inflate(this,R.layout.x3_alone_title_son_item,null);
                LinearLayout.LayoutParams textLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                View v_shape = sonTitle.findViewById(R.id.v_shape);
                shapeSonMap.put(i,v_shape);
                TextView tv_son_title = sonTitle.findViewById(R.id.tv_son_title);
                ImageView iv_help = sonTitle.findViewById(R.id.iv_help);
                sonTitle.setLayoutParams(textLayout);
                tv_son_title.setText(getString(R.string.x3_check_point) + " " + (i + 1)+": " + description);

                List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> answerList = aloneBeans.get(i).questionCarMilesDeductionEntityList;
                if (X3StringUtils.isListEmpty(answerList)) {
                    tv_son_title.setOnClickListener(null);
                    tv_son_title.setCompoundDrawables(null,null,null,null);
                }else {
//                    Drawable pointLeft = ContextCompat.getDrawable(this,R.mipmap.x3_alone_point_answer_icon);
//                    pointLeft.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                    tv_son_title.setCompoundDrawables(null,null,pointLeft,null);
                    iv_help.setVisibility(View.VISIBLE);
                    tv_son_title.setOnClickListener(view -> {
                        // 展示检测点描述
                        showPointDesc(description,answerList);
                    });
                    iv_help.setOnClickListener(view -> {
                        // 展示检测点描述
                        showPointDesc(description,answerList);
                    });
                }

                pointLayout.addView(sonTitle);
                isSaveOne.add(false);
                isStatusOne.add("");
                int titleIndex = j;
                int sonIndex = i;
                String type = aloneBeans.get(i).type;
                String answer = aloneBeans.get(i).answer;
                Log.e("alone_a","answer= " + answer);
                inputAnswer = "";
                switch (type) {
                    case AloneContainerStatusDef.CHOICE:
                        String inputAnswer = X3FileUtils.readFromSdCard(filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_slider_choice" +j+"other"+ i);

                        if(!X3StringUtils.isEmpty(answer)){
                            contents.add(answer);
                            isSaveOne.remove(i);
                            isSaveOne.add(i,true);
                            v_shape.setBackground(ContextCompat.getDrawable(this,R.drawable.x3_process_green));
                        } else if (!X3StringUtils.isEmpty(inputAnswer)) {
                            contents.add(inputAnswer);
                            isSaveOne.remove(i);
                            isSaveOne.add(i,true);
                            v_shape.setBackground(ContextCompat.getDrawable(this,R.drawable.x3_process_green));
                        } else {
                            contents.add("");
                        }

                        AloneChoiceBean aloneChoiceBean = null;
                        if(!X3StringUtils.isEmpty(answer)){
                            aloneChoiceBean = X3AloneChangePagerUtils.aloneChoice(this, aloneBeans.get(i), pointLayout,answer, i);
                        }else{
                            aloneChoiceBean = X3AloneChangePagerUtils.aloneChoice(this, aloneBeans.get(i), pointLayout,inputAnswer, i);
                        }

                        choice_Lists.put(sonIndex,aloneChoiceBean);

                        aloneChoiceBean.getAloneChoiceAdapter().setiOnClickAdapter(content -> {
                            if (!needUpdateMile) {
                                choiceToServiceItem(titleIndex,sonIndex,content);
                                return;
                            }
                            mileDialog = new X3BottomAffirmMileDialog(X3AloneActivity.this);
                            mileDialog.show();
                            mileDialog.changeCancel(false);
                            mileDialog.setWorkBaseId(providerWorkBaseId(),carBean);
                            mileDialog.setiOnClickAffirmMiles((currentMiles1, perMiles1) -> {
                                // 确认完总里程和日均里程了
                                needUpdateMile = false;
                                perMiles = Double.parseDouble(X3StringUtils.formatDouble(perMiles1));
                                currentMiles = Double.parseDouble(X3StringUtils.formatDouble(currentMiles1));
                                choiceToServiceItem(titleIndex,sonIndex,content);
                            });

                        });
                        break;
                    case AloneContainerStatusDef.PERCENT_SLIDER:
                        inputAnswer = X3FileUtils.readFromSdCard(filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_percent_slider" + j + "other" + i);
                        if (!X3StringUtils.isEmpty(answer)){
                            isSaveOne.remove(i);
                            isSaveOne.add(i,true);
                            v_shape.setBackground(ContextCompat.getDrawable(this,R.drawable.x3_process_green));
                            contents.add(answer);
                        } else if (!X3StringUtils.isEmpty(inputAnswer)) {
                            isSaveOne.remove(i);
                            isSaveOne.add(i,true);
                            v_shape.setBackground(ContextCompat.getDrawable(this,R.drawable.x3_process_green));
                            contents.add(inputAnswer);
                        } else {
                            contents.add("");
                        }

                        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> deductionList1 =
                                aloneNewBeans.get(j).questionDetectionTempletQuestionList.get(i).questionCarMilesDeductionEntityList;

                        String tmpAnswer21 = "";
                        if (!X3StringUtils.isEmpty(answer)){
                            tmpAnswer21 = answer;
                        }else{
                            tmpAnswer21 = inputAnswer;
                        }
                        View percentView = X3AloneChangePagerUtils.alonePercentSlider(this,tmpAnswer21,answer,pointLayout,v_shape,deductionList1);

                        EditText et_percent_number = percentView.findViewById(R.id.et_number);
                        percentView.setOnClickListener(view -> {
                            et_percent_number.requestFocus();
                            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                            imm.showSoftInput(et_percent_number, InputMethodManager.SHOW_IMPLICIT);
                            String content = et_percent_number.getText().toString();
                            if (X3StringUtils.isEmpty(content)) {
                                et_percent_number.setSelection(content.length());
                            }
                        });
                        et_percent_number.addTextChangedListener(new X3EdittextWatcher() {
                            @Override
                            protected void textInputAfter(String inputNum) {
                                if (!needUpdateMile) {
                                    inputToServiceItem(titleIndex,sonIndex,type,percentView,v_shape,inputNum);
                                    return;
                                }
                                mileDialog = new X3BottomAffirmMileDialog(X3AloneActivity.this);
                                mileDialog.show();
                                mileDialog.changeCancel(false);
                                mileDialog.setWorkBaseId(providerWorkBaseId(),carBean);
                                mileDialog.setiOnClickAffirmMiles((currentMiles1, perMiles1) -> {
                                    // 确认完总里程和日均里程了
                                    needUpdateMile = false;
                                    perMiles = Double.parseDouble(X3StringUtils.formatDouble(perMiles1));
                                    currentMiles = Double.parseDouble(X3StringUtils.formatDouble(currentMiles1));
                                    inputToServiceItem(titleIndex,sonIndex,type,percentView,v_shape,inputNum);
                                });
                            }
                        });

                        break;
                    case AloneContainerStatusDef.NUMBER:
                        inputAnswer = X3FileUtils.readFromSdCard(filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_number" + j + "other" + i);
                        if(!X3StringUtils.isEmpty(answer)){
                            isSaveOne.remove(i);
                            isSaveOne.add(i,true);
                            v_shape.setBackground(ContextCompat.getDrawable(this,R.drawable.x3_process_green));
                            contents.add(answer);
                        } else if (!X3StringUtils.isEmpty(inputAnswer)) {
                            isSaveOne.remove(i);
                            isSaveOne.add(i,true);
                            v_shape.setBackground(ContextCompat.getDrawable(this,R.drawable.x3_process_green));
                            contents.add(inputAnswer);
                        } else {
                            contents.add("");
                        }

                        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> deductionList =
                                aloneNewBeans.get(j).questionDetectionTempletQuestionList.get(i).questionCarMilesDeductionEntityList;

                        String  tmpAnswer3 = "";
                        if(!X3StringUtils.isEmpty(answer)){
                            tmpAnswer3 = answer;
                        } else {
                            tmpAnswer3 = inputAnswer;
                        }
                        View view =  X3AloneChangePagerUtils.aloneNumber(this, tmpAnswer3, answer, pointLayout, v_shape,deductionList);

                        EditText et_number = view.findViewById(R.id.et_number);
                        ImageView iv_input_del = view.findViewById(R.id.iv_input_del);

                        iv_input_del.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                et_number.setText("");
                                iv_input_del.setVisibility(View.GONE);
                            }
                        });

                        et_number.addTextChangedListener(new X3EdittextWatcher() {
                            @Override
                            protected void textInputAfter(String inputNum) {
                                if (!needUpdateMile) {
                                    inputToServiceItem(titleIndex,sonIndex,type,view,v_shape,inputNum);
                                    return;
                                }
                                mileDialog = new X3BottomAffirmMileDialog(X3AloneActivity.this);
                                mileDialog.show();
                                mileDialog.changeCancel(false);
                                mileDialog.setWorkBaseId(providerWorkBaseId(),carBean);
                                mileDialog.setiOnClickAffirmMiles((currentMiles1, perMiles1) -> {
                                    // 确认完总里程和日均里程了
                                    needUpdateMile = false;
                                    perMiles = Double.parseDouble(X3StringUtils.formatDouble(perMiles1));
                                    currentMiles = Double.parseDouble(X3StringUtils.formatDouble(currentMiles1));
                                    inputToServiceItem(titleIndex,sonIndex,type,view,v_shape,inputNum);
                                });

                            }
                        });
                        break;
                    default:
                        break;
                }

                /**
                 * 创建检测点下的推荐服务项目
                 */
                View pointView = View.inflate(this,R.layout.x3_check_point_service_item,null);
                TextView tv_check_add = pointView.findViewById(R.id.tv_check_add);
                RelativeLayout rl_add = pointView.findViewById(R.id.rl_add);
                pointLayout.addView(pointView);

                /**
                 * 检测点的评论
                 */
                String content = aloneNewBeans.get(j).questionDetectionTempletQuestionList.get(i).evaluation;

                addItemComment(pointLayout,providerWorkBaseId() + "_" + providerToSystem() + j+"_"+ i,content,questionBaseId);

                lv_content.addView(pointLayout);

                LinearLayout.LayoutParams point = (LinearLayout.LayoutParams) pointView.getLayoutParams();
                point.leftMargin = X3ScreenUtils.dipToPx(16,this);
                point.rightMargin = X3ScreenUtils.dipToPx(16,this);
                point.topMargin = X3ScreenUtils.dipToPx(10,this);
                point.bottomMargin = X3ScreenUtils.dipToPx(20,this);
                pointView.setLayoutParams(point);

                tv_check_add.setOnClickListener(v -> {
                    if(!X3Utils.isFastClick()){
                        return;
                    }
                    if(mPresenter != null){
                        AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean beforeBean = getBeforeCuteSliderAlone(type, answerList, inputAnswer);
                        mPresenter.getServiceBaseListLike(questionBaseId,beforeBean.id,providerWorkBaseId(),titleIndex,description,answerList);
                    }
                });
                rl_add.setOnClickListener(v -> tv_check_add.performClick());

                recommendMap.put(aloneBeans.get(i).questionBaseId,pointView);

                List<AloneServiceListBean> drawBean = getAloneServiceBeanByQuestionId(questionBaseId);

                tv_check_add.setVisibility(X3StringUtils.isListEmpty(drawBean) ? View.INVISIBLE : View.VISIBLE);
                if (!X3StringUtils.isListEmpty(drawBean)) {
                    drawCheckService(drawBean,questionBaseId);
                }
            }
            choiceMap.put(j,choice_Lists);
            shapeMap.put(j,shapeSonMap);
            isSave.add(isSaveOne);
            contentList.add(contents);

            pointMap.put(j,pointList);
            al_container.addView(lv_content);
            lv_content.setVisibility(View.VISIBLE);
            hideBeans.add(new AloneHideBean(false,lv_content,titleView.findViewById(R.id.iv_up)));


            /**
             * 检测项的拍照布局
             */
            if (!aloneItemPicOrder){
                addCameraView(j,isCreate);
            }

            /**
             * 添加检测项之间的分割线
             */
            al_container.addView(layoutUtils.getTitleLineView());

            /**
             * 检测系统的评论
             */
//            addEntireComment(j);

            /**
             * 顶部用于顶出上部布局，避免键盘遮挡
             */
            addBottomView(j);
        }

        showSubmitItem();

        if (jumpIndex == -1) {
            return;
        }
        // 如果不等于-1 说明要跳转到某一项
        jumpToItem();


//        showWindManager();
    }

    /**
     * 检测点的评论
     */
    private void addItemComment(LinearLayout lv_content,final String id,String content,long questionBaseId) {
        View view = layoutUtils.getItemCommentView();
        EditText editText = view.findViewById(R.id.ed_item_comment);
        EditeTagBean tagBean = new EditeTagBean();
        tagBean.tagName = "itemComment";
        tagBean.questionBaseId = questionBaseId;
        editText.setTag(tagBean);
        editText.setTextIsSelectable(true);
        editText.setOnFocusChangeListener(this);
//        LinearLayout ll_start = view.findViewById(R.id.ll_start);

//        X3AloneSoundView as_view = view.findViewById(R.id.as_view);
//        TextView tv_end = view.findViewById(R.id.tv_end);

        View rrl_voice = view.findViewById(R.id.rrl_voice);
        rrl_voice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                rrl_voice.setVisibility(View.INVISIBLE);
//                ll_start.setVisibility(ll_start.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
//                itemRequestPermission(editText, rrl_voice, tv_end, ll_start, as_view, id);
                showItemVoiceUI(editText, rrl_voice, tv_end, ll_start, as_view, id);

            }
        });

        if (!X3StringUtils.isEmpty(content)) {
            editText.setText(content);
        } else {
            AloneItemCommentBean daoBean = DaoSessionUtils.getInstance().getAloneItemCommentBean(id);
            if (daoBean != null) {
                editText.setText(daoBean.getComment());
            }
        }

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                adjustBottomViewParams(-10000);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        commentEditextList.add(editText);
        commentMap.put(id, editText);
        lv_content.addView(view);
    }

    private void showItemVoiceUI(EditText editText,View tv_start,View tv_end,View ll_start,X3AloneSoundView as_view,String id){
        rl_voice_content.setVisibility(View.VISIBLE);
        itemRequestPermission(editText, tv_start, tv_end, ll_start, as_view, id);

    }

    /**
     * 检测点语言识别
     */
    private void itemRequestPermission(EditText editText,View tv_start,View tv_end,View ll_start,X3AloneSoundView as_view,String id){

        XXPermissions.with(this)
                .permission(Permission.RECORD_AUDIO)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            // 这里进行语音听写
                            startItemSoundEdit(editText,tv_start,tv_end,ll_start,as_view,id);
//                            tv_start.setVisibility(View.INVISIBLE);
                            ll_start.setVisibility(View.VISIBLE);
                            as_view.startAnim();

//                            new Handler().post(() -> sl_content.fullScroll(ScrollView.FOCUS_DOWN));
                        } else {
                            XXPermissions.startPermissionActivity(X3AloneActivity.this,permissions);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        XXPermissions.startPermissionActivity(X3AloneActivity.this,permissions);
                    }
                });

    }

    /**
     * 保存检测点的评论
     */
    private void saveItemComment(){
        Iterator<Map.Entry<String, EditText>> it = commentMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, EditText> entry = it.next();

            AloneItemCommentBean daoBean = DaoSessionUtils.getInstance().getAloneItemCommentBean(entry.getKey());
            if (daoBean!=null){
                daoBean.setCommentId(entry.getKey());
                daoBean.setComment(entry.getValue().getText().toString().trim());
                DaoSessionUtils.getInstance().updateAloneItemCommentBean(daoBean);
            }else{
                daoBean = new AloneItemCommentBean();
                daoBean.setCommentId(entry.getKey());
                daoBean.setComment(entry.getValue().getText().toString().trim());
                DaoSessionUtils.getInstance().insertAloneItemCommentBean(daoBean);
            }
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus && v instanceof EditText) {
            currentFocusEt = (EditText) v;
//            if (mPresenter != null){
//                EditeTagBean tagBean = (EditeTagBean) v.getTag();
//                if (tagBean != null){
//                    mPresenter.getItemHotComment(tagBean.questionBaseId);
//                }
//            }
        }
    }

    private void setHotComment(String content){
       if(commentEditextList != null && commentEditextList.size() > 0){
           for (int i = 0;i<commentEditextList.size();i++){
                EditText editText = commentEditextList.get(i);
                if(editText.hasFocus()){
                    String c = editText.getText().toString().trim();
                    editText.setText(c + content);
                    editText.setSelection(editText.getText().toString().length());
                }
           }
       }
    }

    View floatRootView;

    private void showWindManager(int y){
        WindowManager.LayoutParams layoutParam = new WindowManager.LayoutParams();
        layoutParam.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParam.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParam.gravity = Gravity.BOTTOM;
        layoutParam.y = y;
        layoutParam.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

        floatRootView = LayoutInflater.from(this).inflate(R.layout.x3_alone_item_comment_history, null);
        ViewPager vp_comment = floatRootView.findViewById(R.id.vp_comment_new);
        IndicatorView iv_view = floatRootView.findViewById(R.id.iv_view);
        RelativeLayout rl_indicator = floatRootView.findViewById(R.id.rl_indicator);

        vp_comment.setVisibility(View.VISIBLE);
        floatRootView.setVisibility(View.INVISIBLE);
        AloneHotCommentHelper.getInstance().setVp(this, vp_comment, iv_view, rl_indicator,new AloneHotCommentHelper.OnHotClick() {
            @Override
            public void onHotClick(String content) {
                setHotComment(content);
                dismissWindowManager();
            }
        });

        if (mPresenter != null && currentFocusEt!=null){
            EditeTagBean tagBean = (EditeTagBean) currentFocusEt.getTag();
            if (tagBean != null){
                vp_comment.post(new Runnable() {
                    @Override
                    public void run() {
                        keyBoardHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mPresenter.getItemHotComment(tagBean.questionBaseId);
                            }
                        },50);
                    }
                });
            }
        }
        keyBoardHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                X3AloneActivity.this.getWindowManager().addView(floatRootView, layoutParam);
            }
        },250);

    }

    int keyboardHeightInPx;
    SoftKeyboardStateHelper softKeyboardStateHelper;
    //键盘高度参数
    private void keyBoardParams(){

        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int keyboardHeightInPx) {
                Log.e("sc_vh","onSoftKeyboardOpened111 height= " + keyboardHeightInPx);
                if (currentFocusEt != null && currentFocusEt.hasFocus()){
                    int pxh = keyboardHeightInPx + X3ScreenUtils.dip2px(0,X3AloneActivity.this);
                    if("PCGM00".equals(android.os.Build.MODEL) && "OP4679".equals( android.os.Build.DEVICE)){
                        adjustBottomViewParams(pxh,X3ScreenUtils.dip2px(40,X3AloneActivity.this));
                    } else {
                        adjustBottomViewParams(pxh,0);
                    }
                    X3AloneActivity.this.keyboardHeightInPx = pxh;
                    showWindManager(pxh);
                }
            }

            @Override
            public void keyBoardHide(int height) {
                Log.e("sc_vh","onSoftKeyboardOpened1111 ");
                dismissWindowManager();
                adjustBottomViewParams(0,0);
            }
        });

//        softKeyboardStateHelper = new SoftKeyboardStateHelper(this.getWindow().getDecorView());
//        softKeyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateHelper.SoftKeyboardStateListener() {
//            @Override
//            public void onSoftKeyboardOpened(int keyboardHeightInPx) {
//                Log.e("sc_vh","onSoftKeyboardOpened ");
//                if (currentFocusEt != null && currentFocusEt.hasFocus()){
//                    int pxh = keyboardHeightInPx-X3StatusBarUtil.getStatusBarHeight(X3AloneActivity.this) + X3ScreenUtils.dip2px(0,X3AloneActivity.this);
//                    adjustBottomViewParams(pxh);
//                    X3AloneActivity.this.keyboardHeightInPx = pxh;
//                    showWindManager(pxh);
//                }
//            }
//
//            @Override
//            public void onSoftKeyboardClosed() {
//                Log.e("sc_vh","onSoftKeyboardClosed ");
//                dismissWindowManager();
//                adjustBottomViewParams(0);
//            }
//        });
    }

    Handler keyBoardHandler = new Handler();
    int ey;
    private void adjustBottomViewParams(int pxH ,int yOffSet) {

        if (currentFocusEt != null) {
            currentFocusEt.getTag();

            int[] location = new int[2];
            currentFocusEt.getLocationOnScreen(location);
            int ex = location[0];
            ey = location[1];
            int height = currentFocusEt.getHeight();
            ey = ey + height;
            sl_content.post(() -> {
                int sh = X3ScreenUtils.getScreenHeight(X3AloneActivity.this);
                int y = sl_content.getScrollY();
                if (-10000 == pxH) {
                    if (pxH != 0 && ey > (sh - keyboardHeightInPx - X3ScreenUtils.dipToPx(100, X3AloneActivity.this))) {
                        sl_content.smoothScrollTo(0, y + X3ScreenUtils.dipToPx(40, X3AloneActivity.this));
                    }
                } else {
                    if (pxH != 0 && ey > (sh - pxH - X3ScreenUtils.dipToPx(100, X3AloneActivity.this))) {
                        Log.e("sc_vh", "sl_content.getScrollY() = " + y);
                        Log.e("sc_vh", "sl_conte = " + (y + pxH + X3ScreenUtils.dipToPx(100, X3AloneActivity.this)));
                        sl_content.smoothScrollTo(0, y + (yOffSet + pxH + X3ScreenUtils.dipToPx(100, X3AloneActivity.this) + ey - sh));
                    }
                }

            });
        }

    }

    private void dismissWindowManager(){
        try {
            this.getWindowManager().removeViewImmediate(floatRootView);
            floatRootView = null;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 检测系统的评论
     */
//    private void addEntireComment(int j){
//        if (j == aloneNewBeans.size() - 1) {
//            LinearLayout lv_comment = new LinearLayout(this);
//            LinearLayout.LayoutParams commentParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//            commentParams.bottomMargin = X3ScreenUtils.dipToPx(30,this);
//            lv_comment.setLayoutParams(commentParams);
//            lv_comment.setOrientation(LinearLayout.VERTICAL);
//
//            // 增加评价功能
//            View commentView = View.inflate(this,R.layout.x3_alone_title_item,null);
//            TextView comment = commentView.findViewById(R.id.tv_title);
//            ImageView iv_up1 = commentView.findViewById(R.id.iv_up);
//            iv_up1.setImageResource(R.mipmap.x3_iv_alone_down);
//            int finalJ = j;
//            commentView.setOnClickListener(view -> {
//                boolean show = hideBeans.get(finalJ + 1).isShow();
//                AloneHideBean aloneHideBean = hideBeans.get(finalJ + 1);
//                if (show) {
//                    // 正在显示要隐藏
//                    aloneHideBean.getLinearLayout().setVisibility(View.VISIBLE);
//                    aloneHideBean.setShow(false);
//                    hideBeans.get(finalJ + 1).getIv_up().setImageResource(R.mipmap.x3_iv_alone_down);
//                    sl_content.post(() -> sl_content.fullScroll(View.FOCUS_DOWN));
//                }else {
//                    hideBeans.get(finalJ + 1).getIv_up().setImageResource(R.mipmap.x3_iv_alone_up);
//                    aloneHideBean.getLinearLayout().setVisibility(View.GONE);
//                    aloneHideBean.setShow(true);
//                }
//                hideBeans.remove(finalJ + 1);
//                hideBeans.add(finalJ + 1,aloneHideBean);
//
//                if (inputBean == null) {
//                    return;
//                }
//                X3Utils.hideKeyboard(inputBean.getEditText().getWindowToken(),this);
//            });
//
//            LinearLayout.LayoutParams commentLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, X3ScreenUtils.dipToPx(60,this));
//            commentLayout.bottomMargin = X3ScreenUtils.dipToPx(10, this);
//            commentView.setLayoutParams(commentLayout);
//            comment.setText(getString(R.string.x3_user_comments));
//
//            al_container.addView(commentView);
//
//            View editView = View.inflate(this,R.layout.x3_alone_edit_sound_item,null);
//            LinearLayout.LayoutParams editLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//            editView.setLayoutParams(editLayout);
//
//            EditText editText = editView.findViewById(R.id.et_input);
//            LinearLayout ll_start = editView.findViewById(R.id.ll_start);
//            TextView tv_end = editView.findViewById(R.id.tv_end);
//            TextView tv_start = editView.findViewById(R.id.tv_sound);
//            X3AloneSoundView as_view = editView.findViewById(R.id.as_view);
//
////                editText.setInputType(TYPE_TEXT_FLAG_MULTI_LINE);
////                editText.setSingleLine(false);
//
//            String content = X3FileUtils.readFromSdCard(filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_edit");
//            if (!X3StringUtils.isEmpty(content)) {
//                editText.setText(content);
//                editText.setSelection(content.length());
//            }else if (!X3StringUtils.isEmpty(evaluation)) {
//                editText.setText(evaluation);
//                editText.setSelection(evaluation.length());
//            }
//
//            lv_comment.addView(editView);
//            al_container.addView(lv_comment);
//            hideBeans.add(new AloneHideBean(false,lv_comment,iv_up1));
//            inputBean = new EditInputBean(editText, editText.getText().toString(),ll_start,tv_start,tv_end,as_view);
//
//            inputBean.getEditText().addTextChangedListener(new X3EdittextWatcher() {
//                @Override
//                protected void textInputAfter(String content) {
//                    inputBean.setContent(content);
//
//                    String s = inputBean.getEditText().getText().toString();
//                    if (X3StringUtils.isEmpty(s)) {
//                        // 空数据
//                        editText.setBackground(ContextCompat.getDrawable(X3AloneActivity.this,R.drawable.x3_alone_choice_no_select_bg));
//                    }else {
//                        editText.setBackground(ContextCompat.getDrawable(X3AloneActivity.this,R.drawable.x3_edit_shape_bg));
//                    }
//                    showSubmitItem();
//                }
//            });
//
//            // 开始语音识别
//            tv_start.setOnClickListener(view -> XXPermissions.with(this)
//                    .permission(Permission.RECORD_AUDIO)
//                    .permission(Permission.Group.STORAGE)
//                    .request(new OnPermissionCallback() {
//                        @Override
//                        public void onGranted(List<String> permissions, boolean all) {
//                            if(all){
//                                // 这里进行语音听写
//                                startSoundEdit();
//                                tv_start.setVisibility(View.GONE);
//                                ll_start.setVisibility(View.VISIBLE);
//                                as_view.startAnim();
//
//                                new Handler().post(() -> sl_content.fullScroll(ScrollView.FOCUS_DOWN));
//                            }else {
//                                XXPermissions.startPermissionActivity(X3AloneActivity.this,permissions);
//                            }
//                        }
//
//                        @Override
//                        public void onDenied(List<String> permissions, boolean never) {
//                            XXPermissions.startPermissionActivity(X3AloneActivity.this,permissions);
//                        }
//                    }));
//
//
//        }
//    }

    /**
     * 顶部用于顶出上部布局，避免键盘遮挡
     */
    private void addBottomView(int j){
//        if (j == aloneNewBeans.size() - 1) {
//            v_bottom = layoutUtils.getBottomView();
//            al_container.addView(v_bottom);
//        }
    }

    /**
     * 添加拍照布局
     * @param titleIndex
     * @param isCreate
     */
    private void addCameraView(long titleIndex,boolean isCreate) {
        /**
         * 创建录音和拍照的view
         */
        X3MyRecyclerview photoRecy = layoutUtils.getPhotoRecyclerview();
        photoRecy.addItemDecoration(new AverageGapItemDecoration(10,10,0));
        List<AloneImageAndRecordBean> imageList = new ArrayList<>();
        imageList.clear();
        /**
         * 先从缓存中取
         */
        AloneImageBean aloneImageBean = DaoSessionUtils.getInstance().searchByImageOnlyLogo(providerWorkBaseId() + providerTitle() + titleIndex);
        if (aloneImageBean != null) {
            List<AloneImageAndRecordBean> mList = aloneImageBean.getMList();
            if (!X3StringUtils.isListEmpty(mList)) {
                for (int y = 0; y < mList.size(); y++) {
                    AloneImageAndRecordBean imageAndRecordBean = mList.get(y);
                    if (AloneUploadStatus.UPLODING == imageAndRecordBean.getUploadStatus() && isCreate) {
                        imageAndRecordBean.setUploadStatus(AloneUploadStatus.UPLOADING_FAILED);
                    }
                    mList.remove(y);
                    mList.add(y,imageAndRecordBean);
                    imageList.add(imageAndRecordBean);
                }
                aloneImageBean.setMList(mList);
                DaoSessionUtils.getInstance().updateAloneAndRecord(aloneImageBean);
            }
        } else {
            /**
             * 从网络获取
             */
            List<String> resourceUrlList = aloneNewBeans.get((int) titleIndex).resourceUrlList;
            List<Long> idList = aloneNewBeans.get((int) titleIndex).resourceIdList;
            if (X3StringUtils.isListEmpty(idList)) {
                idList = new ArrayList<>();
            }
            if (X3StringUtils.isListEmpty(resourceUrlList)) {
                resourceUrlList = new ArrayList<>();
            }
            for (int rid = 0; rid < resourceUrlList.size(); rid++) {
                long resId = 0;
                if (idList != null && rid < idList.size()) {
                    resId = idList.get(rid);
                }
                AloneImageAndRecordBean imageAndRecordBean = new AloneImageAndRecordBean(resourceUrlList.get(rid),resourceUrlList.get(rid),resId, AloneUploadStatus.UPLOADING_SUCCESS);
                imageList.add(imageAndRecordBean);
            }
            /**
             * 存储到本地数据库
             */
            aloneImageBean = new AloneImageBean();
            aloneImageBean.setOnlyLogo(providerWorkBaseId() + providerTitle() + titleIndex);
            aloneImageBean.setMList(imageList);
            DaoSessionUtils.getInstance().insertAloneImageAndRecordBean(aloneImageBean);
        }

        X3CameraNewAdapter cameraNewAdapter = new X3CameraNewAdapter(this, true, (int) titleIndex,9);
        photoRecy.setAdapter(cameraNewAdapter);
        cameraNewAdapter.changeData(imageList);
        cameraNewAdapter.setiOnItemCameraClick(this);

        al_container.addView(photoRecy);

        cameraAllList.put(titleIndex,new AloneCarBean(photoRecy, cameraNewAdapter));

        photoRecy.setVisibility(View.VISIBLE);

    }

    private void jumpToItem() {
        int titleIndex = -1;
        int sonIndex = -1;
        for (int i = 0; i < aloneNewBeans.size(); i++) {
            List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> questionList = aloneNewBeans.get(i).questionDetectionTempletQuestionList;
            for(int j = 0; j < questionList.size(); j++) {
                AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean questionBean = questionList.get(j);
                if (jumpIndex == questionBean.questionBaseId) {
                    titleIndex = i;
                    sonIndex = j;
                    break;
                }
            }
        }
        Log.e("SSSS","计算出要跳转哪一项:" + titleIndex + "::" + sonIndex + "::" + jumpIndex);
        if (titleIndex == -1 || sonIndex == -1) {
            return;
        }

        iOnClickJumpToIndex(titleIndex,sonIndex);
    }

    /**
     * 选择题 选择后计算
     * @param titleIndex
     * @param sonIndex
     */
    private void choiceToServiceItem(long titleIndex, long sonIndex,String content) {
        isSave.get((int) titleIndex).remove((int) sonIndex);
        isSave.get((int) titleIndex).add((int) sonIndex, true);

        Log.e("selected_status","选择题选择后 答题状态= " + isSave.get((int) titleIndex).get((int) sonIndex)
                + " (int) titleIndex " + (int) titleIndex
                + " (int) sonIndex " + (int) sonIndex
                + " content " +content
        );

        contentList.get((int) titleIndex).remove((int)sonIndex);
        contentList.get((int) titleIndex).add((int) sonIndex,content);

        String choiceAnswer = X3FileUtils.readFromSdCard(filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_slider_choice" + titleIndex + "other" + sonIndex);
        String answer = aloneNewBeans.get((int) titleIndex).questionDetectionTempletQuestionList.get((int) sonIndex).answer;
        String description = aloneNewBeans.get((int) titleIndex).questionDetectionTempletQuestionList.get((int) sonIndex).description;
        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> answerList = aloneNewBeans.get((int) titleIndex).questionDetectionTempletQuestionList.get((int) sonIndex).questionCarMilesDeductionEntityList;

        if (X3StringUtils.isEmpty(choiceAnswer) && isSubmit) {
            choiceAnswer = answer;
        }

        cuteSliderAlone(titleIndex,sonIndex,content,description,getBeforeCuteSliderAlone(AloneContainerStatusDef.CHOICE,answerList,choiceAnswer),getBeforeCuteSliderAlone(AloneContainerStatusDef.CHOICE, answerList, content));

        showSubmitItem();

        keepAlone(titleIndex,sonIndex,AloneContainerStatusDef.CHOICE,content);

        if (shapeMap == null) {
            return;
        }
        HashMap<Integer, View> shapeHashMap = shapeMap.get(titleIndex);

        if (shapeHashMap == null) {
            return;
        }
        View v_shape = shapeHashMap.get(sonIndex);
        if (v_shape == null) {
            return;
        }
        // 选中数据 需要将小红点变成小绿点
        v_shape.setBackground(ContextCompat.getDrawable(this,R.drawable.x3_process_green));
    }

    /**
     * 数值题与百分比题 输入后计算
     * @param titleIndex
     * @param sonIndex
     * @param type
     * @param view
     * @param v_shape
     * @param inputNum
     */
    private void inputToServiceItem(int titleIndex, int sonIndex, String type, View view, View v_shape, String inputNum) {
        if (!X3StringUtils.isEmpty(inputNum)) {
            if (inputNum.endsWith(".")) {
                inputNum = inputNum.replace(".","");
            }
        }
        if (!X3StringUtils.isListEmpty(contentList) && titleIndex < contentList.size()) {
            List<String> strings = contentList.get(titleIndex);
            if (!X3StringUtils.isListEmpty(strings) && sonIndex < strings.size()) {
                strings.remove(sonIndex);
                strings.add(sonIndex,inputNum);
            }
            contentList.remove(titleIndex);
            contentList.add(titleIndex,strings);
        }

        TextView tv_status = view.findViewById(R.id.tv_status);
        TextView tv_error = view.findViewById(R.id.tv_error);
        ImageView iv_error = view.findViewById(R.id.iv_error);
        EditText et_number = view.findViewById(R.id.et_number);
        TextView tv_percent = null;

        if (AloneContainerStatusDef.PERCENT_SLIDER.equals(type)) {
            tv_percent = view.findViewById(R.id.tv_percent);
        }

        iv_error.setVisibility(View.GONE);
        tv_error.setVisibility(View.GONE);
        if (X3StringUtils.isEmpty(inputNum)) {
            et_number.setHint(getString(R.string.x3_please_input));
            tv_status.setVisibility(View.GONE);
            view.setBackground(ContextCompat.getDrawable(X3AloneActivity.this, R.drawable.x3_alone_choice_no_select_bg));
            v_shape.setBackground(ContextCompat.getDrawable(X3AloneActivity.this,R.drawable.x3_red_shape));
            View vContent = view.findViewById(R.id.rl_input);
            if (vContent!=null){
                vContent.setBackground(null);
            }
            if (AloneContainerStatusDef.PERCENT_SLIDER.equals(type) && tv_percent != null) {
                tv_percent.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                tv_percent.setTextColor(ContextCompat.getColor(X3AloneActivity.this,R.color.c333));
            }
            try {
                ImageView iv_input_r = view.findViewById(R.id.iv_input_r);
                iv_input_r.setImageResource(R.mipmap.x3_alone_input_grey);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            if (AloneContainerStatusDef.PERCENT_SLIDER.equals(type) && tv_percent != null) {
                tv_percent.setGravity(Gravity.CENTER_VERTICAL);
            }
            et_number.setHint("");

            tv_status.setVisibility(View.VISIBLE);
            v_shape.setBackground(ContextCompat.getDrawable(X3AloneActivity.this,R.drawable.x3_process_green));
            List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> deductionList = aloneNewBeans.get(titleIndex).questionDetectionTempletQuestionList.get(sonIndex).questionCarMilesDeductionEntityList;
            AloneDeductionBean percentBean = X3AloneChangePagerUtils.getPercentNumberStatus(Double.parseDouble(inputNum), deductionList);
            if (AloneSubmitStatus.MINOR.equals(percentBean.status)) {
                tv_status.setText("（" + getString(R.string.x3_minor_notice) + "）");
                view.setBackground(ContextCompat.getDrawable(X3AloneActivity.this, R.drawable.x3_alone_number_minor_bg));
                et_number.setTextColor(Color.parseColor("#F3850F"));
                tv_status.setTextColor(Color.parseColor("#F3850F"));
                if (AloneContainerStatusDef.PERCENT_SLIDER.equals(type) && tv_percent != null) {
                    tv_percent.setTextColor(Color.parseColor("#F3850F"));
                }
                try {
                    ImageView iv_input_r = view.findViewById(R.id.iv_input_r);
                    iv_input_r.setImageResource(R.mipmap.x3_alone_input_warning);
                    View vContent = view.findViewById(R.id.rl_input);
                    vContent.setBackground(null);

                    View ll_error = view.findViewById(R.id.ll_error);
                    ll_error.setVisibility(View.GONE);

                    ImageView iv_input_del = view.findViewById(R.id.iv_input_del);
                    iv_input_del.setVisibility(View.GONE);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else if (AloneSubmitStatus.MAJOR.equals(percentBean.status)) {
                tv_status.setText("（" + getString(R.string.x3_major_notice) + "）");
                view.setBackground(ContextCompat.getDrawable(X3AloneActivity.this, R.drawable.x3_alone_number_dangerous_bg));
                et_number.setTextColor(Color.parseColor("#F64458"));
                tv_status.setTextColor(Color.parseColor("#F64458"));
                if (AloneContainerStatusDef.PERCENT_SLIDER.equals(type) && tv_percent != null) {
                    tv_percent.setTextColor(Color.parseColor("#F64458"));
                }
                try {
                    ImageView iv_input_r = view.findViewById(R.id.iv_input_r);
                    iv_input_r.setImageResource( R.mipmap.x3_alone_input_danger);
                    View vContent = view.findViewById(R.id.rl_input);
                    vContent.setBackground(null);

                    View ll_error = view.findViewById(R.id.ll_error);
                    ll_error.setVisibility(View.GONE);

                    ImageView iv_input_del = view.findViewById(R.id.iv_input_del);
                    iv_input_del.setVisibility(View.GONE);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else if (AloneSubmitStatus.DANGEROUS.equals(percentBean.status)) {
                tv_status.setText("（" + getString(R.string.x3_error_notice) + "）");
                view.setBackground(ContextCompat.getDrawable(X3AloneActivity.this, R.drawable.x3_alone_number_dangerous_bg));
                et_number.setTextColor(Color.parseColor("#F64458"));
                tv_status.setTextColor(Color.parseColor("#F64458"));
                if (AloneContainerStatusDef.PERCENT_SLIDER.equals(type) && tv_percent != null) {
                    tv_percent.setTextColor(Color.parseColor("#F64458"));
                }
                try {
                    ImageView iv_input_r = view.findViewById(R.id.iv_input_r);
                    iv_input_r.setImageResource( R.mipmap.x3_alone_input_danger);
                    View vContent = view.findViewById(R.id.rl_input);
                    vContent.setBackground(null);
                    View ll_error = view.findViewById(R.id.ll_error);
                    ll_error.setVisibility(View.GONE);
                    ImageView iv_input_del = view.findViewById(R.id.iv_input_del);
                    iv_input_del.setVisibility(View.GONE);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else if (AloneSubmitStatus.PASS.equals(percentBean.status)){
                tv_status.setText("（" + getString(R.string.x3_normal_notice) + "）");
                view.setBackground(ContextCompat.getDrawable(X3AloneActivity.this, R.drawable.x3_alone_number_normal_bg));
                et_number.setTextColor(Color.parseColor("#18BE6B"));
                tv_status.setTextColor(Color.parseColor("#18BE6B"));
                try {
                    ImageView iv_input_r = view.findViewById(R.id.iv_input_r);
                    iv_input_r.setImageResource( R.mipmap.x3_alone_input_normal);
                    View vContent = view.findViewById(R.id.rl_input);
                    vContent.setBackground(null);
                    View ll_error = view.findViewById(R.id.ll_error);
                    ll_error.setVisibility(View.GONE);

                    ImageView iv_input_del = view.findViewById(R.id.iv_input_del);
                    iv_input_del.setVisibility(View.GONE);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if (AloneContainerStatusDef.PERCENT_SLIDER.equals(type) && tv_percent != null) {
                    tv_percent.setTextColor(Color.parseColor("#18BE6B"));
                }

            }else {
                iv_error.setVisibility(View.VISIBLE);
                tv_error.setVisibility(View.VISIBLE);
                et_number.setTextColor(ContextCompat.getColor(X3AloneActivity.this, R.color.c333));
//                view.setBackground(ContextCompat.getDrawable(X3AloneActivity.this, R.drawable.x3_alone_number_error_notice));
                view.setBackground(null);
                View vContent = view.findViewById(R.id.rl_input);
                if (vContent!=null){
                    vContent.setBackground(ContextCompat.getDrawable(X3AloneActivity.this, R.drawable.x3_alone_number_error_bg2));
                }
                tv_status.setVisibility(View.GONE);
                if (AloneContainerStatusDef.PERCENT_SLIDER.equals(type) && tv_percent != null) {
                    tv_percent.setTextColor(ContextCompat.getColor(X3AloneActivity.this,R.color.c333));
                }
                try {
                    View ll_error = view.findViewById(R.id.ll_error);
                    ll_error.setVisibility(View.VISIBLE);
                    ImageView iv_input_del = view.findViewById(R.id.iv_input_del);
                    iv_input_del.setVisibility(View.VISIBLE);
                    ImageView iv_input_r = view.findViewById(R.id.iv_input_r);
                    iv_input_r.setImageResource(R.mipmap.x3_alone_input_grey);

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        isSave.get((int) titleIndex).remove((int)sonIndex);
        isSave.get((int) titleIndex).add((int) sonIndex, !X3StringUtils.isEmpty(inputNum));

        showSubmitItem();

        String answer = aloneNewBeans.get((int) titleIndex).questionDetectionTempletQuestionList.get((int) sonIndex).answer;
        String description = aloneNewBeans.get((int) titleIndex).questionDetectionTempletQuestionList.get((int) sonIndex).description;
        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> answerList = aloneNewBeans.get(titleIndex).questionDetectionTempletQuestionList.get(sonIndex).questionCarMilesDeductionEntityList;

        String numberAnswer = "";
        switch (type) {
            case AloneContainerStatusDef.NUMBER:
                numberAnswer = X3FileUtils.readFromSdCard(filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_number" + titleIndex + "other" + sonIndex);

                break;
            case AloneContainerStatusDef.PERCENT_SLIDER:
                numberAnswer = X3FileUtils.readFromSdCard(filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_percent_slider" + titleIndex + "other" + sonIndex);

                break;
        }

        if (X3StringUtils.isEmpty(numberAnswer) && isSubmit) {
            numberAnswer = answer;
        }

        cuteSliderAlone(titleIndex,sonIndex,inputNum,description,getBeforeCuteSliderAlone(type,answerList,numberAnswer),getBeforeCuteSliderAlone(type,answerList,inputNum));

        keepAlone(titleIndex,sonIndex,type,inputNum);

    }

    /**
     * 绘制检测点下所关联的推荐服务项目
     * @param listBean
     * @param questionBaseId
     */
    public void drawCheckService(List<AloneServiceListBean> listBean,long questionBaseId) {
        tv_service_num.setVisibility(X3StringUtils.isListEmpty(serviceList) ? View.GONE : View.VISIBLE);

        View serviceView = recommendMap.get(questionBaseId);
        RelativeLayout rl_add = serviceView.findViewById(R.id.rl_add);
        LinearLayout ll_check_add = serviceView.findViewById(R.id.ll_check_add);
        TextView tv_check_add = serviceView.findViewById(R.id.tv_check_add);
        TextView tv_check = serviceView.findViewById(R.id.tv_check);

        rl_add.setVisibility(X3StringUtils.isListEmpty(listBean) ? View.VISIBLE : View.GONE);
        ll_check_add.setVisibility(X3StringUtils.isListEmpty(listBean) ? View.GONE : View.VISIBLE);
        ll_check_add.removeAllViews();
//        tv_check_add.setText(X3StringUtils.isListEmpty(listBean) ? getString(R.string.add) : getString(R.string.add_and_edit));
        tv_check.setText((X3StringUtils.isListEmpty(listBean) || listBean.size() == 1) ? getString(R.string.x3_service_recommended) : getString(R.string.x3_service_recommendeds));
        tv_check_add.setVisibility(X3StringUtils.isListEmpty(listBean) ? View.INVISIBLE : View.VISIBLE);

        if (X3StringUtils.isListEmpty(listBean)) {
            return;
        }

        for (int i = 0; i < listBean.size(); i++) {
            AloneServiceListBean drawBean = listBean.get(i);
            if (drawBean == null) {
                continue;
            }
            long optionsId = drawBean.getOptionsId();

            View view = View.inflate(this,R.layout.x3_check_add_service_item,null);
            View divider = view.findViewById(R.id.v_divider);
            if(i==listBean.size()-1){
                divider.setVisibility(View.GONE);
            }
            ll_check_add.addView(view);
            LinearLayout.LayoutParams viewLayout = (LinearLayout.LayoutParams) view.getLayoutParams();
            if (i == 0) {
                viewLayout.topMargin = 0;
                viewLayout.bottomMargin = 0;
            }else {
                viewLayout.topMargin = X3ScreenUtils.dipToPx(10,this);
                viewLayout.bottomMargin = 0;
            }
            view.setLayoutParams(viewLayout);

            RelativeLayout rl_container = view.findViewById(R.id.rl_container);
            TextView tv_add_service = view.findViewById(R.id.tv_add_service);
            TextView tv_miles = view.findViewById(R.id.tv_miles);
            ImageView iv_del = view.findViewById(R.id.iv_del);

            iv_del.setVisibility(optionsId == 0 ? View.VISIBLE : View.GONE);

            if (optionsId == 0) {
                iv_del.setOnClickListener(view1 -> {
                    deleteServiceItem(drawBean,questionBaseId);
                });
            }else {
                iv_del.setOnClickListener(null);
            }

            tv_add_service.setText(drawBean.getTouchServiceBaseName());
            String reductionType = drawBean.getReductionType();
            if(!X3StringUtils.isEmpty(reductionType)){
                if(reductionType.equals("MILE")){
                    long safeMiles = (long) (drawBean.getRecommendSafeMiles() - currentMiles);
                    if(safeMiles <= 0){
                        tv_miles.setText(getString(R.string.x3_now_to_work));
                        tv_miles.setTextColor(ContextCompat.getColor(this,R.color.bg_F64444));
                    }else {
                        tv_miles.setText(String.format(getString(R.string.km_after_notice),safeMiles + km));
                    }

                }else{
                    String warningDate = drawBean.getWarningDate();
                    try {
                        int differMonth = X3DateUtils.getDifferMonth(new Date(System.currentTimeMillis()), X3DateUtils.stringToDate(warningDate, "yyyy-MM-dd HH:mm:ss"));
                        if(differMonth == 0){
                            tv_miles.setText(getString(R.string.x3_now_to_work));
                            tv_miles.setTextColor(ContextCompat.getColor(this,R.color.bg_F64444));
                        }else if(differMonth == 1){
                            tv_miles.setText(String.format(getString(R.string.how_many_month),differMonth));
                        }else {
                            tv_miles.setText(String.format(getString(R.string.how_many_months),differMonth));
                        }

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }

            rl_container.setOnClickListener(v -> {
                if(!needUpdateMile){
                    modifyMileOrTime(drawBean, drawBean.getReductionType());
                }else {
                    X3BottomAffirmMileDialog mileDialog = new X3BottomAffirmMileDialog(X3AloneActivity.this);
                    mileDialog.show();
                    mileDialog.setWorkBaseId(providerWorkBaseId(),carBean);
                    mileDialog.setiOnClickAffirmMiles((currentMiles1, perMiles1) -> {
                        // 确认完总里程和日均里程了
                        needUpdateMile = false;
                        perMiles = Double.parseDouble(X3StringUtils.formatDouble(perMiles1));
                        currentMiles = Double.parseDouble(X3StringUtils.formatDouble(currentMiles1));
                        saveService(serviceList);
                        drawAllCheckView(false);
                        modifyMileOrTime(drawBean, drawBean.getReductionType());
                    });
                }
            });
        }

    }

    /**
     * 删除检测点下手动添加的推荐服务项目
     * @param drawBean
     */
    private void deleteServiceItem(AloneServiceListBean drawBean,long questionBaseId) {
        if (drawBean == null) {
            return;
        }
        if (X3StringUtils.isListEmpty(serviceList)) {
            return;
        }
        Iterator<AloneServiceListBean> serviceBean = serviceList.iterator();
        while (serviceBean.hasNext()) {
            AloneServiceListBean next = serviceBean.next();
            if (!next.getTouchServiceSn().equals(drawBean.getTouchServiceSn())) {
                continue;
            }
            List<Long> touchQuestionBaseIdList = next.getTouchQuestionBaseIdList();
            if (!X3StringUtils.isListEmpty(touchQuestionBaseIdList) && touchQuestionBaseIdList.contains(questionBaseId)) {
                touchQuestionBaseIdList.remove(touchQuestionBaseIdList.indexOf(questionBaseId));
            }

            List<AloneServiceListBean.IdBean> idList = next.getQuestionAndOptionIdVOList();
            if (X3StringUtils.isListEmpty(idList)) {
                continue;
            }
            Iterator<AloneServiceListBean.IdBean> iterator = idList.iterator();
            while (iterator.hasNext()) {
                AloneServiceListBean.IdBean idNext = iterator.next();
                if (idNext.getQuestionBaseId() == questionBaseId){
                    iterator.remove();
                    break;
                }
            }
            if (X3StringUtils.isListEmpty(touchQuestionBaseIdList)) {
                serviceBean.remove();
            }
        }

        drawCheckService(getAloneServiceBeanByQuestionId(questionBaseId),questionBaseId);
        if (mPresenter != null) {
            mPresenter.saveDetectionService(serviceList);
        }
    }

    /**
     * 根据检测点id 获取检测点下所关联的推荐服务项目
     * @param questionBaseId
     * @return
     */
    protected List<AloneServiceListBean> getAloneServiceBeanByQuestionId(long questionBaseId) {
        List<AloneServiceListBean> questionList = new ArrayList<>();
        if (X3StringUtils.isListEmpty(serviceList)) {
            return new ArrayList<>();
        }
        for (int i = 0; i < serviceList.size(); i++) {
            AloneServiceListBean listBean = serviceList.get(i);
            if (listBean == null) {
                continue;
            }

            List<AloneServiceListBean.IdBean> idList = listBean.getQuestionAndOptionIdVOList();
            if (X3StringUtils.isListEmpty(idList)) {
                continue;
            }

            for (int j = 0; j < idList.size(); j++) {
                AloneServiceListBean.IdBean idBean = idList.get(j);
                if (questionBaseId == idBean.getQuestionBaseId()) {
                    listBean.setQuestionBaseId(questionBaseId);
                    listBean.setOptionsId(idBean.getOptionsId());
                    questionList.add(listBean);
                    break;
                }
            }
        }

        return questionList;
    }

    /**
     * 在削减之前 需要将之前的添加过的系统推荐服务项目进行加回 然后再进行新阶段的削减
     * @param type
     */
    private AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean getBeforeCuteSliderAlone(String type,
                         List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> answerList,
                         String answer) {

        AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean afterBean = new AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean();
        switch (type) {
            case AloneContainerStatusDef.CHOICE:
                afterBean = X3AloneChangePagerUtils.getCurrentChoiceTouchList(answer, answerList);

                break;
            case AloneContainerStatusDef.PERCENT_SLIDER:
                double percentAnswer = (!X3StringUtils.isEmpty(answer) && X3StringUtils.isAloneNum(answer)) ? Double.parseDouble(answer) : -1;
                afterBean = X3AloneChangePagerUtils.getPercentNumberTouchList(percentAnswer, answerList);
                break;
            case AloneContainerStatusDef.NUMBER:
                double numberAnswer = (!X3StringUtils.isEmpty(answer) && X3StringUtils.isAloneNum(answer)) ? Double.parseDouble(answer) : -1;
                afterBean = X3AloneChangePagerUtils.getCurrentNumberTouchList(numberAnswer, answerList);

                break;
        }

        return afterBean;
    }

    /**
     * 点击检测点 展示检测点答案以及描述
     * @param mList
     */
    private void showPointDesc(String title,List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> mList) {
        if (answerDialog == null) {
            answerDialog = new X3BottomAloneAnswerDialog(this);
        }
        answerDialog.show();
        answerDialog.changeData(title,mList);

    }

    /**
     * 检测点的语音识别
      */
    private void startItemSoundEdit(EditText editText,View tv_start,View tv_end,View ll_start,X3AloneSoundView as_view,String id) {

//        evaluaFile = X3FileUtils.getStoragePath(this, X3FileUtils.RECORD_STORAGE_PATH) + System.currentTimeMillis()+"evalua.wav";
//        evaluaFile = X3FileUtils.getStoragePath(this, X3FileUtils.RECORD_STORAGE_PATH) + System.currentTimeMillis()+"evalua.wav";

//        String filePath = itemVoiceFileMap.put(id,X3FileUtils.getStoragePath(this, X3FileUtils.RECORD_STORAGE_PATH) + id+System.currentTimeMillis()+"evalua.wav");
        String filePath =  X3FileUtils.getStoragePath(this, X3FileUtils.RECORD_STORAGE_PATH) + id+System.currentTimeMillis()+"evalua.wav";

        mIat = SpeechRecognizer.createRecognizer(this, i -> Log.e("SSSS","初始化："+i));

        //设置语法ID和 SUBJECT 为空，以免因之前有语法调用而设置了此参数；或直接清空所有参数，具体可参考 DEMO 的示例。
        mIat.setParameter(SpeechConstant.CLOUD_GRAMMAR, null );
        mIat.setParameter(SpeechConstant.SUBJECT, null );
        //设置返回结果格式，目前支持json,xml以及plain 三种格式，其中plain为纯听写文本内容
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        //此处engineType为“cloud”
        mIat.setParameter( SpeechConstant.ENGINE_TYPE, "cloud");
        //设置语音输入语言，zh_cn为简体中文
        if (LanguageUtiles.isZhRCN()) {
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        }else {
            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        }

        //设置结果返回语言
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 设置语音前端点:静音超时时间，单位ms，即用户多长时间不说话则当做超时处理
        //取值范围{1000～10000}
        mIat.setParameter(SpeechConstant.VAD_BOS, "10000");
        //设置语音后端点:后端点静音检测时间，单位ms，即用户停止说话多长时间内即认为不再输入，
        //自动停止录音，范围{0~10000}
        mIat.setParameter(SpeechConstant.VAD_EOS, "10000");
        //设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT,"1");

        mIat.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, filePath);

        //开始识别，并设置监听器
        mIat.startListening(new RecognizerListener() {
            @Override
            public void onVolumeChanged(int i, byte[] bytes) {

            }

            @Override
            public void onBeginOfSpeech() {
//                evaluaNum = 1;
            }

            @Override
            public void onEndOfSpeech() {
//                ll_start.setVisibility(View.GONE);
                rl_voice_content.setVisibility(View.GONE);

                tv_start.setVisibility(View.VISIBLE);
                as_view.stopAnim();

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (mPresenter != null) {
                                mPresenter.uploadWavAws(new File(filePath),id);
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                },200);

            }

            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                SpeechBean speechBean = gson.fromJson(recognizerResult.getResultString(), SpeechBean.class);
                List<SpeechBean.WsBean> ws = speechBean.getWs();
                String strContent = "";
                for (SpeechBean.WsBean wsBean: ws) {
                    strContent = strContent + wsBean.getCw().get(0).getW() ;
                }
                String oldCotent = editText.getText().toString() ;
                String result = oldCotent + strContent;
                editText.setText(result);
                if (!X3StringUtils.isEmpty(result)) {
                    editText.setSelection(result.length());
                }

//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            if (mPresenter != null) {
//                                mPresenter.uploadWavAws(new File(filePath),id);
//                            }
//                        }catch (Exception e){
//                            e.printStackTrace();
//                        }
//                    }
//                },1000);

            }

            @Override
            public void onError(SpeechError speechError) {
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {
                if(i == 22003){
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (mPresenter != null) {
                                    mPresenter.uploadWavAws(new File(filePath),id);
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    },200);
                }
            }
        });

        tv_end.setOnClickListener(view -> {
            tv_start.setVisibility(View.VISIBLE);
            ll_start.setVisibility(View.GONE);
            if (mIat == null) {
                X3ToastUtils.showMessage("语音初始化出错！");
                return;
            }
            mIat.stopListening();
//            new Handler().post(() -> sl_content.fullScroll(ScrollView.FOCUS_DOWN));
        });

    }

    private void stopListening(){
        ll_start.setVisibility(View.GONE);
        rl_voice_content.setVisibility(View.GONE);
        if (mIat == null) {
            X3ToastUtils.showMessage("语音初始化出错！");
            return;
        }
        mIat.stopListening();
    }


    /**
     * 语音听写
     */
//    private void startSoundEdit() {
//
//        evaluaFile = X3FileUtils.getStoragePath(this, X3FileUtils.RECORD_STORAGE_PATH) + System.currentTimeMillis()+"evalua.wav";
//
//        mIat = SpeechRecognizer.createRecognizer(this, i -> Log.e("SSSS","初始化："+i));
//
//        //设置语法ID和 SUBJECT 为空，以免因之前有语法调用而设置了此参数；或直接清空所有参数，具体可参考 DEMO 的示例。
//        mIat.setParameter(SpeechConstant.CLOUD_GRAMMAR, null );
//        mIat.setParameter(SpeechConstant.SUBJECT, null );
//        //设置返回结果格式，目前支持json,xml以及plain 三种格式，其中plain为纯听写文本内容
//        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
//
//        //此处engineType为“cloud”
//        mIat.setParameter( SpeechConstant.ENGINE_TYPE, "cloud");
//        //设置语音输入语言，zh_cn为简体中文
//        if (LanguageUtiles.isZhRCN()) {
//            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
//        }else {
//            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
//        }
//
//        //设置结果返回语言
//        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
//        // 设置语音前端点:静音超时时间，单位ms，即用户多长时间不说话则当做超时处理
//        //取值范围{1000～10000}
//        mIat.setParameter(SpeechConstant.VAD_BOS, "10000");
//        //设置语音后端点:后端点静音检测时间，单位ms，即用户停止说话多长时间内即认为不再输入，
//        //自动停止录音，范围{0~10000}
//        mIat.setParameter(SpeechConstant.VAD_EOS, "10000");
//        //设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
//        mIat.setParameter(SpeechConstant.ASR_PTT,"1");
//
//        mIat.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
//        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, evaluaFile);
//
//        //开始识别，并设置监听器
//        mIat.startListening(new RecognizerListener() {
//            @Override
//            public void onVolumeChanged(int i, byte[] bytes) {
//
//            }
//
//            @Override
//            public void onBeginOfSpeech() {
//                evaluaNum = 1;
//            }
//
//            @Override
//            public void onEndOfSpeech() {
//                inputBean.getLl_start().setVisibility(View.GONE);
//                inputBean.getTv_start().setVisibility(View.VISIBLE);
//                inputBean.getAs_view().stopAnim();
//
//            }
//
//            @Override
//            public void onResult(RecognizerResult recognizerResult, boolean b) {
//                SpeechBean speechBean = gson.fromJson(recognizerResult.getResultString(), SpeechBean.class);
//                List<SpeechBean.WsBean> ws = speechBean.getWs();
//                String strContent = "";
//                for (SpeechBean.WsBean wsBean: ws) {
//                    strContent = strContent + wsBean.getCw().get(0).getW();
//                }
//                inputBean.setContent((inputBean != null ? inputBean.getContent() : "") + strContent);
//                inputBean.getEditText().setText(inputBean.getContent());
//                String content = inputBean.getContent();
//                if (!X3StringUtils.isEmpty(content)) {
//                    inputBean.getEditText().setSelection(content.length());
//                }
//            }
//
//            @Override
//            public void onError(SpeechError speechError) {
//            }
//
//            @Override
//            public void onEvent(int i, int i1, int i2, Bundle bundle) {
//
//            }
//        });
//
//        inputBean.getTv_end().setOnClickListener(view -> {
//            inputBean.getTv_start().setVisibility(View.VISIBLE);
//            inputBean.getLl_start().setVisibility(View.GONE);
//            if (mIat == null) {
//                X3ToastUtils.showMessage("语音初始化出错！");
//                return;
//            }
//            mIat.stopListening();
//
//            new Handler().post(() -> sl_content.fullScroll(ScrollView.FOCUS_DOWN));
//        });
//
//    }

    @Override
    public void keepAlone(long titleIndex,long sonIndex,String type, String content) {
//        X3FileUtils.writeTxtToFile(inputBean.getContent() + "", filePath,providerWorkBaseId() + "Alone" + providerToSystem() + "_edit");

        switch (type) {
            case AloneContainerStatusDef.CHOICE:
                X3FileUtils.writeTxtToFile(content,filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_slider_choice" + titleIndex + "other" + sonIndex);

                break;
            case AloneContainerStatusDef.PERCENT_SLIDER:
                X3FileUtils.writeTxtToFile(content, filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_percent_slider" + titleIndex + "other" + sonIndex);

                break;
            case AloneContainerStatusDef.NUMBER:
                X3FileUtils.writeTxtToFile(content, filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_number" + titleIndex + "other" + sonIndex);

                break;
        }
    }

    /**
     * 最后提交之前 需要把答案全部装填起来
     */
    public void addSubmitData(String content,long sonIndex,String questionStatus,String itemComment,long soundId) {

        if (!X3StringUtils.isEmpty(content)) {
            aloneBeans.get((int) sonIndex).options = content;
            aloneBeans.get((int) sonIndex).evaluation = itemComment;
            aloneBeans.get((int) sonIndex).evaluationSoundId = soundId;
        } else {
            if (!isSubmit) {
                X3ToastUtils.showMessage(getString(R.string.x3_answer_all_after_submit));
                return;
            }
        }
        aloneBeans.get((int) sonIndex).questionBaseStatus = questionStatus;
    }

    @Override
    public void submitAlone(List<AloneNewBean.ItemQuestionListBean> aloneNewBeans) {
        this.aloneNewBeans = aloneNewBeans;

        /**
         * 保存每一个检测点的评论到本地数据库
         */
        saveItemComment();

        for (int j = 0; j < aloneNewBeans.size(); j++) {
            aloneBeans = aloneNewBeans.get(j).questionDetectionTempletQuestionList;
            for (int i = 0; i < aloneBeans.size(); i++) {
                List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> carList = aloneBeans.get(i).questionCarMilesDeductionEntityList;
                String questionBaseStatus = "";
                String answer = aloneBeans.get(i).answer;
                AloneItemCommentBean daoBean = DaoSessionUtils.getInstance().getAloneItemCommentBean(providerWorkBaseId() + "_" + providerToSystem() + j+"_"+ i);

                switch (aloneBeans.get(i).type) {
                    case AloneContainerStatusDef.CHOICE:
                        String s8 = X3FileUtils.readFromSdCard(filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_slider_choice"+j+"other" + i);

                        String choiceAnswer = s8;
                        if (X3StringUtils.isEmpty(s8)) {
                            choiceAnswer = answer;
                        }

                        questionBaseStatus = X3AloneChangePagerUtils.getCurrentChoiceStatus(choiceAnswer,carList).status;
                        //Log.e("SSSS","选择题答案："+j+"::"+i+"::"+choiceAnswer+"::"+questionBaseStatus);
                        addSubmitData(choiceAnswer,i,questionBaseStatus,daoBean.getComment(),daoBean.getEvaluationSoundId());

                        break;
                    case AloneContainerStatusDef.PERCENT_SLIDER:
                        String p1 = X3FileUtils.readFromSdCard(filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_percent_slider" + j+"other" +i);

                        String answerPercent = answer;
                        String contentPercent = "";
                        double percentNumberAnswer = 0;
                        if (!X3StringUtils.isEmpty(p1)) {
                            contentPercent = p1;
                            percentNumberAnswer = Double.parseDouble(p1);
                        }else if (!X3StringUtils.isEmpty(answerPercent)) {
                            contentPercent = answerPercent;
                            percentNumberAnswer = Double.parseDouble(answerPercent);
                        }

                        questionBaseStatus = X3AloneChangePagerUtils.getPercentNumberStatus(percentNumberAnswer,carList).status;

                        if (AloneSubmitStatus.ILLEGAL.equals(questionBaseStatus)) {
                            X3ToastUtils.showMessage(getString(R.string.x3_number_error));
                            btn_submit.reset();
                            return;
                        }

                        addSubmitData(contentPercent,i,questionBaseStatus,daoBean.getComment(),daoBean.getEvaluationSoundId());

                        break;
                    case AloneContainerStatusDef.NUMBER:
                        String s14 = X3FileUtils.readFromSdCard(filePath, providerWorkBaseId() + "Alone" + providerToSystem() + "_number" + j+"other" +i);

                        String submitAnswer = answer;
                        double numberAnswer = 0;
                        String content = "";
                        if (!X3StringUtils.isEmpty(s14)) {
                            content = s14;
                            numberAnswer = Double.parseDouble(s14);
                        }else if (!X3StringUtils.isEmpty(submitAnswer)) {
                            content = submitAnswer;
                            numberAnswer = Double.parseDouble(submitAnswer);
                        }

                        questionBaseStatus = X3AloneChangePagerUtils.getCurrentNumberStatus(numberAnswer,carList).status;

                        if (AloneSubmitStatus.ILLEGAL.equals(questionBaseStatus)) {
                            X3ToastUtils.showMessage(getString(R.string.x3_number_error));
                            btn_submit.reset();
                            return;
                        }

                        addSubmitData(content,i,questionBaseStatus,daoBean.getComment(),daoBean.getEvaluationSoundId());

                        break;
                    default:
                        aloneBeans.get(i).options = ("0");
                        aloneBeans.get(i).questionBaseStatus = (AloneSubmitStatus.PASS);
                        break;
                }

            }
        }

        // 上传评论录音
//        if (evaluaNum == 1) {
//            if (mPresenter != null) {
//                //mPresenter.requestQiNiuToken(evaluaFile);
//                mPresenter.uploadWavAws(new File(evaluaFile),"");
//            }
//        }

        handler.postDelayed(runnable,200);
    }

    @Override
    public void showSuccessDialog() {
        btn_submit.reset();
//        if (reportStatus == 1) {
//            ToastUtils.showMessage(getString(R.string.submit_notice) + "");
//        }
        back();
    }

    @Override
    public void showItemHotCommentSuc(List<String> comments) {
        if(!X3StringUtils.isListEmpty(comments)){
            if(floatRootView != null){
                AloneHotCommentHelper.getInstance().changeVpData(comments,floatRootView);
            }
        }
    }

    /**
     * 检查是否可以提交
     */
    public void showSubmitItem() {
        int isAllSubmit = 0;
        int allLength = 0;
        for (int j = 0; j < aloneNewBeans.size(); j++) {
            List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> questionList = aloneNewBeans.get(j).questionDetectionTempletQuestionList;
            List<Boolean> booleans = isSave.get(j);
            for (int i = 0; i < questionList.size(); i++) {
                allLength++;
                if (!booleans.get(i)) {
                    continue;
                }
                isAllSubmit++;
            }
        }

        // 存储当前已经答完的检测点数量
        SpHelper.saveData(mgtCreate + providerWorkBaseId() + providerToSystem() + "AnswerAmount",isAllSubmit);

        showAleadyAnswerNum(aloneNewBeans);

        if(isAllSubmit == allLength){
            tv_mask_commit.setVisibility(View.GONE);
        } else {
            tv_mask_commit.setVisibility(View.VISIBLE);
        }

        btn_submit.changeBtnStatus(isAllSubmit == allLength);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {

            if (evaluaNum == evaluaAlreadyNum) {
//                long id = inputBean.getSoundId() == 0 ? evaluaId : inputBean.getSoundId();

                if (handler != null) {
                    handler.removeCallbacks(this);
                }
                if (mPresenter != null) {
                    mPresenter.submitAloneData(aloneNewBeans,0);
                }

            }else {
                handler.postDelayed(this,1000);
            }
        }
    };

    Handler handler = new Handler();

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
        if (alreadyAloneServiceDialog != null) {
            alreadyAloneServiceDialog.dismiss();
        }
        hideLoading();
        if (handler != null) {
            handler = null;
        }
        if (mIat != null) {
            mIat.stopListening();
            mIat.cancel();
        }
        if (layoutUtils != null) {
            layoutUtils.onDestory();
        }
        super.onDestroy();
    }

    @Override
    public void getAwsSoundIdSuccess(boolean isSuccess, AwsFileBean awsFileBean,String itemId) {
        Log.e("xxxxxxxx","awsFileBean = " + awsFileBean.toString());

        if (!X3StringUtils.isEmpty(itemId)) { // 检测点上传语音
            if (isSuccess) {
                if (awsFileBean != null) {
                    long id = awsFileBean.id;
                    Log.e("xxx","id = " + id);
                    AloneItemCommentBean daoBean = DaoSessionUtils.getInstance().getAloneItemCommentBean(itemId);
                    if (daoBean!=null){
                        daoBean.setEvaluationSoundId(id);
                        DaoSessionUtils.getInstance().updateAloneItemCommentBean(daoBean);
                        Log.e("xxxxxxxx","updateAloneItemCommentBean id = " + id);
                    }else{
                        daoBean = new AloneItemCommentBean();
                        daoBean.setCommentId(itemId);
                        daoBean.setEvaluationSoundId(id);
                        DaoSessionUtils.getInstance().insertAloneItemCommentBean(daoBean);
                        Log.e("xxxxxxxx","insertAloneItemCommentBean id = " + id);
                    }
                } else {

                }
            } else {

                Log.i("qiniu", "Upload Fail");
            }
        } else {
            if (isSuccess) {
                if (awsFileBean != null) {
                    long id = awsFileBean.id;
//                    inputBean.setSoundId(id);
                    evaluaAlreadyNum++;
                } else {
                    evaluaNum--;
                }
            } else {
                evaluaNum--;
                Log.i("qiniu", "Upload Fail");
            }
        }

    }

    @Override
    public void finish() {

        super.finish();
        overridePendingTransition(0, 0);
    }

    /**
     * 点击title 实现title展开或者隐藏
     * @param index
     */
    @Override
    public void iOnAloneClickTitle(int index) {
//        boolean show = hideBeans.get((int)index).isShow();
//        AloneHideBean aloneHideBean = hideBeans.get((int)index);
//        if (show) {
//            // 正在显示要隐藏
//            aloneHideBean.getLinearLayout().setVisibility(View.VISIBLE);
//            aloneHideBean.setShow(false);
//            aloneHideBean.getIv_up().setImageResource(R.mipmap.x3_iv_alone_down);
//        }else {
//            aloneHideBean.getIv_up().setImageResource(R.mipmap.x3_iv_alone_up);
//            aloneHideBean.getLinearLayout().setVisibility(View.GONE);
//            aloneHideBean.setShow(true);
//        }
//        hideBeans.remove(index);
//        hideBeans.add(index,aloneHideBean);
    }

    /**
     * 点击上面的数字项跳转到顶部
     * @param titleIndex
     * @param index
     */
    @Override
    public void iOnClickJumpToIndex(int titleIndex,int index) {
        if (!pointMap.containsKey(titleIndex)) {
            return;
        }
        List<LinearLayout> pointList = pointMap.get(titleIndex);
        if (X3StringUtils.isListEmpty(pointList)) {
            return;
        }
        if (index >= pointList.size()) {
            return;
        }
        if (hideBeans.get(titleIndex).getLinearLayout().getVisibility() == View.GONE) {
            iOnAloneClickTitle(titleIndex);
        }
        /**
         * 先回到顶部
         */
        sl_content.scrollTo(0,0);

        sl_content.post(() -> {
            LinearLayout pointLayout = pointList.get(index);
            int[] location = new int[2];
            pointLayout.getLocationOnScreen(location);
            sl_content.smoothScrollTo(0,location[1] - X3ScreenUtils.dipToPx(50, X3AloneActivity.this) - X3StatusBarUtil.getStatusBarHeight(X3AloneActivity.this));
        });
    }

    @Override
    public void iOnSubmitAlone() {
        iOnClickAffirm();
    }

    @Override
    public void iOnClickPass(int type,int titleIndex,int index){
        if (type == 1){//全部通过
            showPassDialog(aloneNewBeans, true);
        } else { //通过单个检测点
            // 检测点标记通过
            List<AloneNewBean.ItemQuestionListBean> passBean = new ArrayList<>();
            passBean.add(aloneNewBeans.get(titleIndex));
            showPassDialog(passBean,false);
        }
    }

    /**
     * 拍照
     * @param index
     * @param index
     */
    @Override
    public void iOnItemCameraClick(int index) {
        this.titleIndex = index;
        XXPermissions.with(X3AloneActivity.this)
                .permission(Permission.CAMERA)
                .permission(Permission.RECORD_AUDIO)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        // 当前已经拍摄的照片或者视频的数量
                        int size = 0;
                        size = cameraAllList.get(titleIndex).getCameraAdapter().getImageList().size();

                        if (9 - size == 0) {
                            X3ToastUtils.showMessage(String.format(getString(R.string.x3_upload_mast_nine),9));
                            return;
                        }
                        if(all){
                            layoutUtils.startCamera(X3AloneActivity.this,fl_parent,aloneNewBeans.get((int) titleIndex).id,
                                    providerWorkBaseId(), 9 - size,
                                    aloneNewBeans.get(index).normalResourceUrl,false,
                                    cameraBean -> onGetPictureOrVideo(cameraBean));

                        }else {
                            X3ToastUtils.showMessage(getString(R.string.x3_camera_permiss) + "");
                            XXPermissions.startPermissionActivity(X3AloneActivity.this,permissions);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        X3ToastUtils.showMessage(getString(R.string.x3_camera_permiss) + "");
                        XXPermissions.startPermissionActivity(X3AloneActivity.this,permissions);
                    }
                });
    }

    /**
     * 删除
     * @param
     * @param index
     */
    @Override
    public void iOnDeleteClick(long resId,int position,int index,String path) {
        SpHelper.saveData(providerWorkBaseId()+providerToSystem() + "",true);
        if (mPresenter != null) {
            mPresenter.saveOrUpdateWorkResource(resId,index,false,path);
        }
    }

    /**
     * 上传失败后 点击重新上传图片
     * @param path
     * @param titleIndex
     * @param imageIndex
     */
    @Override
    public void iOnAgainUploadImage(String path, int titleIndex, int imageIndex) {
        if (mPresenter != null) {
            mPresenter.uploadImageAws(new File(path),titleIndex);
            //mPresenter.requestQiNiuToken(path, titleIndex,false);
        }
    }

    @Override
    public void iOnDeleteImage(int titleIndex, List<AloneImageAndRecordBean> mList) {
        AloneImageBean aloneImageBean = DaoSessionUtils.getInstance().searchByImageOnlyLogo(providerWorkBaseId() + providerTitle() + titleIndex);
        if (aloneImageBean != null) {
            aloneImageBean.setMList(mList);
            DaoSessionUtils.getInstance().updateAloneAndRecord(aloneImageBean);
        }
        showSubmitItem();
    }

    /**
     * 更新图片成功
     * @param aloneImageAndRecordBean
     * @param titleIndex
     * isUpload 是否是上传图片  false为删除图片
     */
    @Override
    public void getUpdatePictureSuccess(AloneImageAndRecordBean aloneImageAndRecordBean, long titleIndex,boolean isUpload) {
        if (aloneImageAndRecordBean == null) {
            return;
        }
        List<AloneImageAndRecordBean> cameraList = cameraAllList.get(titleIndex).getCameraAdapter().getCameraList();
        AloneImageBean aloneImageBean = DaoSessionUtils.getInstance().searchByImageOnlyLogo(providerWorkBaseId() + providerTitle() + titleIndex);

        if (aloneImageBean == null) {
            return;
        }
        if (X3StringUtils.isListEmpty(cameraList)) {
            return;
        }
        int refreshIndex = -1;
        String currentPath = aloneImageAndRecordBean.getPath();
        String currentHttpPath = aloneImageAndRecordBean.getHttpPath();

        for (int i = 0; i < cameraList.size(); i++) {
            String path = cameraList.get(i).getPath();
            String httpPath = cameraList.get(i).getHttpPath();

            long uploadStatus = cameraList.get(i).getUploadStatus();
            if (X3StringUtils.isEmpty(path) && X3StringUtils.isEmpty(httpPath)) {
                continue;
            }
            if (isUpload) {
                if (!X3StringUtils.isEmpty(currentHttpPath) && currentHttpPath.equals(httpPath)
                        && (uploadStatus == AloneUploadStatus.UPLODING || uploadStatus == AloneUploadStatus.UPLOADING_FAILED)) {
                    refreshIndex = i;
                    break;
                }
                if (!X3StringUtils.isEmpty(currentPath) && currentPath.equals(path)
                        && (uploadStatus == AloneUploadStatus.UPLODING || uploadStatus == AloneUploadStatus.UPLOADING_FAILED)) {
                    refreshIndex = i;
                    break;
                }
            }else {
                if (!X3StringUtils.isEmpty(currentHttpPath) && currentHttpPath.equals(httpPath)) {
                    refreshIndex = i;
                    break;
                }
                if (!X3StringUtils.isEmpty(currentPath) && currentPath.equals(path)) {
                    refreshIndex = i;
                    break;
                }
            }
        }
        if (refreshIndex == -1) {
            return;
        }

        long uploadStatus = aloneImageAndRecordBean.getUploadStatus();
        long realStatus = ((uploadStatus == AloneUploadStatus.UPLODING || uploadStatus == AloneUploadStatus.UPLOADING_SUCCESS) ? AloneUploadStatus.UPLOADING_SUCCESS : AloneUploadStatus.UPLOADING_FAILED);
        aloneImageAndRecordBean.setUploadStatus(realStatus);

        List<AloneImageAndRecordBean> mList = aloneImageBean.getMList();
        if (isUpload) {
            if (!X3StringUtils.isListEmpty(mList) && refreshIndex < mList.size()) {
                mList.remove(refreshIndex);
                mList.add(refreshIndex,aloneImageAndRecordBean);
            }

        }else {
            if (!X3StringUtils.isListEmpty(mList) && refreshIndex < mList.size()) {
                mList.remove(refreshIndex);
            }
        }

        aloneImageBean.setMList(mList);
        DaoSessionUtils.getInstance().updateAloneAndRecord(aloneImageBean);
        cameraAllList.get(titleIndex).getCameraAdapter().changeData(mList);

        showSubmitItem();
    }

    /**
     * 从相册中选取图片 或者拍照 数据都会从这个方法进入
     * @param cameraBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetPictureOrVideo(CameraBean cameraBean) {
        if (cameraBean == null) {
            return;
        }
        /**
         * 这个值判断是否拍照了 或者删除了 都要更新
         */
        SpHelper.saveData(providerWorkBaseId()+providerToSystem() + "",true);

        /**
         * 判断是否检测点展示了 如果没有展示的话 那么将要展示
         */
        if (hideBeans.get((int) titleIndex).getLinearLayout().getVisibility() == View.GONE) {
            iOnAloneClickTitle((int) titleIndex);
        }
        switch ((int) cameraBean.resultCode) {
            //图片或者视频
            case X3Constent.CODE_CAMERA_REQUEST:
            case X3Constent.CODE_GALLERY_REQUEST:
                if (cameraBean.cameraData == null) {
                    return;
                }
                List<String> pList = (List<String>) cameraBean.cameraData;

                List<AloneImageAndRecordBean> addList = new ArrayList<>();
                for (String path : pList) {
                    Log.e("SSSS","查看视频地址:" + path);
                    if (!X3StringUtils.isEmpty(path) && mPresenter != null) {
                        cameraAllList.get(titleIndex).getCameraAdapter().addData(new AloneImageAndRecordBean(path,"",0,AloneUploadStatus.UPLODING));
                        showSubmitItem();
                        addList.add(new AloneImageAndRecordBean(path,"",0,AloneUploadStatus.UPLODING));
                        mPresenter.uploadImageAws(new File(path),titleIndex);
                        //mPresenter.requestQiNiuToken(path,titleIndex,false);
                    }
                }

                /**
                 * 存储到本地数据库
                 */
                AloneImageBean aloneImageBean = DaoSessionUtils.getInstance().searchByImageOnlyLogo(providerWorkBaseId() + providerTitle() + titleIndex);
                if (aloneImageBean == null) {
                    aloneImageBean = new AloneImageBean();
                    aloneImageBean.setOnlyLogo(providerWorkBaseId() + providerTitle() + titleIndex);
                    aloneImageBean.setMList(addList);
                    DaoSessionUtils.getInstance().insertAloneImageAndRecordBean(aloneImageBean);
                }else {
                    List<AloneImageAndRecordBean> mList = aloneImageBean.getMList();
                    mList.addAll(addList);
                    aloneImageBean.setMList(mList);
                    DaoSessionUtils.getInstance().updateAloneAndRecord(aloneImageBean);
                }
                break;
            case X3Constent.CODE_ALONE_ADD_SERVICE_REQUEST:
                if (cameraBean.cameraData == null) {
                    return;
                }

                if (mPresenter != null) {
                    mPresenter.getDetectionServiceListForRefresh();
                }
                break;
            case X3Constent.CODE_ALONE_CHANGE_NEED_UPDATE:
                needUpdateMile = false;
                if (mPresenter != null) {
                    mPresenter.obtainAloneBean();
                }

                break;
            case X3Constent.CODE_ALONE_IMAGE_TO_QUESTION:
                if (cameraBean.cameraData == null) {
                    return;
                }
                HashMap<String,Long> tagNumMap = (HashMap<String, Long>) cameraBean.cameraData;
                if (tagNumMap == null) {
                    return;
                }
                tagToQuestion(tagNumMap);
                break;
            default:
                break;
        }
    }

    /**
     * 根据选中的标签 去自动选中题目
     * @param tagNumMap
     */
    private void tagToQuestion(HashMap<String, Long> tagNumMap) {
        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> questionList = aloneNewBeans.get((int) titleIndex).questionDetectionTempletQuestionList;
        if (X3StringUtils.isListEmpty(questionList)) {
            return;
        }
        for (int i = 0; i < questionList.size(); i++) {
            String type = questionList.get(i).type;
            if (!AloneContainerStatusDef.CHOICE.equals(type)) {
                continue;
            }
            List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> deductionList = questionList.get(i).questionCarMilesDeductionEntityList;
            if (X3StringUtils.isListEmpty(deductionList)) {
                continue;
            }
            // 求出出现次数最大的tag
            int tagMaxNum = -1;
            String tagMax = "";
            for (int dIndex = 0; dIndex < deductionList.size(); dIndex++) {
                String optionDescription = deductionList.get(dIndex).optionDescription;
                if (!tagNumMap.containsKey(optionDescription)) {
                    continue;
                }
                int tagNum = Integer.parseInt(tagNumMap.get(optionDescription)+"");
                if (tagMaxNum <= tagNum) {
                    tagMaxNum = tagNum;
                    tagMax = optionDescription;
                }
            }
            if (tagMaxNum == -1) {
                continue;
            }
            choiceToServiceItem(titleIndex,i,tagMax);
            if (choiceMap == null) {
                continue;
            }
            X3AloneChoiceAdapter choiceAdapter = choiceMap.get(Integer.parseInt(titleIndex+"")).get(i).getAloneChoiceAdapter();
            if (choiceAdapter != null) {
                choiceAdapter.changeSelectChoice(tagMax);
            }
        }
    }

    @Override
    public Boolean isViewFinishing() {
        return isFinishing();
    }

    @Override
    public String providerTitle() {
        return getIntent().getStringExtra("title");
    }

    @Override
    public void saveService(List<AloneServiceListBean> mList) {
        this.serviceList = mList;
//        tv_service_num.setVisibility(X3StringUtils.isListEmpty(mList) ? View.GONE : View.VISIBLE);
        v_tips.setVisibility(X3StringUtils.isListEmpty(mList) ? View.GONE : View.VISIBLE);

        if (X3StringUtils.isListEmpty(serviceList)) {
            return;
        }

        for (int i = 0; i < serviceList.size(); i++) {
            AloneServiceListBean listBean1 = serviceList.get(i);
            serviceList.remove(i);
            listBean1.setPerMiles(perMiles);
            listBean1.setCurrentMiles(currentMiles);
            serviceList.add(i,listBean1);
        }
    }

    @Override
    public void getDetectionServiceListForRefresh(List<AloneServiceListBean> mList) {
        this.serviceList = mList;
        drawAllCheckView(true);
    }

    @Override
    public void getEvaluationContent(String evaluation) {
        this.evaluation = evaluation;
    }

    @Override
    public Context getContext() {
        return this;
    }


    @Override
    public void getServiceBaseListLikeSus(List<TestRecommendBean> list,long questionBaseId, long titleIndex,String decTitle,long questionOptionId,
                                          List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> deductionList) {
        if(X3StringUtils.isListEmpty(list)){
            showAloneDialog(questionBaseId,  titleIndex,decTitle,questionOptionId,deductionList);
        }else{
            X3RecommendForYouPopWindow recommendForYouPopWindow = new X3RecommendForYouPopWindow(X3AloneActivity.this,list);
            recommendForYouPopWindow.showPopupWindow();
            recommendForYouPopWindow.setOnRfyClick(new X3RecommendForYouPopWindow.IOnRfyClick() {
                @Override
                public void iOnClickAll() {//查看全部
                    if(recommendForYouPopWindow != null){
                        recommendForYouPopWindow.dismissPop();
                    }
                    showAloneDialog(questionBaseId, titleIndex,decTitle,questionOptionId,deductionList);
                }

                @Override
                public void iOnItemClick(TestRecommendBean testRecommendBean) {//服务项目点击事件
                    if(recommendForYouPopWindow != null){
                        recommendForYouPopWindow.dismissPop();
                    }
                    aloneServiceListBean = X3AloneServiceSearchUtils.searchAloneServiceBean(serviceList, testRecommendBean.sn);
                    if(!needUpdateMile){
                        aloneServiceListBean = getAloneServiceListBean(testRecommendBean,questionBaseId,decTitle,deductionList);
                        modifyMileOrTime(aloneServiceListBean, aloneServiceListBean.getReductionType());
                    }else {
                        X3BottomAffirmMileDialog mileDialog = new X3BottomAffirmMileDialog(X3AloneActivity.this);
                        mileDialog.show();
                        mileDialog.setWorkBaseId(providerWorkBaseId(),carBean);
                        mileDialog.setiOnClickAffirmMiles((currentMiles1, perMiles1) -> {
                            // 确认完总里程和日均里程了
                            needUpdateMile = false;
                            perMiles = Double.parseDouble(X3StringUtils.formatDouble(perMiles1));
                            currentMiles = Double.parseDouble(X3StringUtils.formatDouble(currentMiles1));
                            saveService(serviceList);
                            drawAllCheckView(false);

                            aloneServiceListBean = getAloneServiceListBean(testRecommendBean,questionBaseId,decTitle,deductionList);
                            modifyMileOrTime(aloneServiceListBean, aloneServiceListBean.getReductionType());
                        });
                    }
                }
            });
        }

    }

    private AloneServiceListBean getAloneServiceListBean(TestRecommendBean testRecommendBean, long questionBaseId, String decTitle, List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> deductionList){
        List<Long> idList = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        List<AloneServiceListBean.IdBean> idBeans = new ArrayList<>();
        if(aloneServiceListBean == null){
            aloneServiceListBean = new AloneServiceListBean();
            aloneServiceListBean.setWorkBaseId(providerWorkBaseId());
            aloneServiceListBean.setRecommendSafeMiles(0);
            aloneServiceListBean.setTouchServiceBaseName(testRecommendBean.name);
            aloneServiceListBean.setTouchServiceSn(testRecommendBean.sn);
            aloneServiceListBean.setCurrentMiles(currentMiles);
            aloneServiceListBean.setPerMiles(perMiles);
            aloneServiceListBean.setReductionType("MILE");
            idBeans.add(new AloneServiceListBean.IdBean(questionBaseId,0));
            aloneServiceListBean.setQuestionAndOptionIdVOList(idBeans);
            if (!idList.contains(questionBaseId)) {
                idList.add(questionBaseId);
            }

            titleList.add(decTitle);
            aloneServiceListBean.setSystemList(new ArrayList<>());
            aloneServiceListBean.setTouchQuestionBaseDescriptionList(titleList);
            aloneServiceListBean.setTouchQuestionBaseIdList(idList);
        }else {
            idList = aloneServiceListBean.getTouchQuestionBaseIdList();
            titleList = aloneServiceListBean.getTouchQuestionBaseDescriptionList();
            idBeans = aloneServiceListBean.getQuestionAndOptionIdVOList();

            if (X3StringUtils.isListEmpty(idBeans)) {
                idBeans = new ArrayList<>();
            }
            if (X3StringUtils.isListEmpty(idList)) {
                idList = new ArrayList<>();
            }
            if (X3StringUtils.isListEmpty(titleList)) {
                titleList = new ArrayList<>();
            }
            if (!idList.contains(questionBaseId)) {
                idList.add(questionBaseId);
            }
            if (!titleList.contains(decTitle)) {
                titleList.add(decTitle);
            }
            aloneServiceListBean.setTouchQuestionBaseDescriptionList(titleList);
            aloneServiceListBean.setTouchQuestionBaseIdList(idList);
            idBeans.add(new AloneServiceListBean.IdBean(questionBaseId,0));
            aloneServiceListBean.setQuestionAndOptionIdVOList(idBeans);
            aloneServiceListBean.setOptionsId(0);
            aloneServiceListBean.setQuestionBaseId(questionBaseId);
        }
        return aloneServiceListBean;
    }

    private void modifyMileOrTime(AloneServiceListBean changeServiceBean,String remindType) {
        if (changeServiceBean == null) {
            return;
        }
        if (changeServiceBean.getCurrentMiles() <= 0 && changeServiceBean.getPerMiles() <= 1) {
            changeServiceBean.setPerMiles(perMiles);
            changeServiceBean.setCurrentMiles(currentMiles);
        }
        X3NewBottomMileOrTimeDialog mileOrTimeDialog = new X3NewBottomMileOrTimeDialog(this,1);
        mileOrTimeDialog.show();
        mileOrTimeDialog.showCurrentMile(changeServiceBean,remindType);
        mileOrTimeDialog.setiOnAffirmSelect(new X3NewBottomMileOrTimeDialog.IOnAffirmSelect() {
            @Override
            public void iOnAffirmMiles(AloneServiceListBean listBean) {
                boolean isHave = false;
                List<AloneServiceListBean> newCacheList = serviceList;
                for (int i = 0; i < newCacheList.size(); i++) {
                    AloneServiceListBean aloneServiceListBean = newCacheList.get(i);
                    if (aloneServiceListBean.getTouchServiceSn().equals(listBean.getTouchServiceSn())) {
                        isHave = true;
                        newCacheList.remove(i);
                        newCacheList.add(i,listBean);
                        break;
                    }
                }
                if (!isHave) {
                    newCacheList.add(listBean);
                }
                System.out.println("集合  "+ newCacheList.toString());
                saveService(newCacheList);
                drawAllCheckView(false);
            }

            @Override
            public void iOnPickerDismiss() {

            }
        });
    }
    @Override
    public void saveSoundId(long evaluaId) {
        this.evaluaId = evaluaId;
    }

    @Override
    public void iOnClickAffirm() {
        SpHelper.saveData(providerWorkBaseId() + providerToSystem() + "ISRED",false);
        mPresenter.saveDetectionServiceList(serviceList);
    }

    /**
     * TODO 标记通过的检测点
     */
    @Override
    public void iBtnAffirmClick() {
        if (X3StringUtils.isListEmpty(passAloneBean)) {
            return;
        }
        if (!isAll) {
            AloneNewBean.ItemQuestionListBean itemBean = passAloneBean.get(0);
            int index = aloneNewBeans.indexOf(itemBean);
            if (index == -1) {
                return;
            }
            setPassBean(itemBean,index);
            clearCloneItemServiceItem(itemBean);
            switchAloneSystem(aloneNewBeans,false);

            statusDialog.changeData(isStatus, aloneNewBeans,contentList, (int)allNum, (int)aleadyAnswerNum, btn_submit.getTextContent(), btn_submit.getStatus());

            return;
        }
        for (int i = 0; i < aloneNewBeans.size(); i++) {
            AloneNewBean.ItemQuestionListBean itemBean = aloneNewBeans.get(i);
            setPassBean(itemBean,i);
            clearCloneItemServiceItem(itemBean);
        }
//        clearAllRecServiceItem();
        switchAloneSystem(aloneNewBeans,false);


        statusDialog.changeData(isStatus, aloneNewBeans,contentList, (int)allNum, (int)aleadyAnswerNum, btn_submit.getTextContent(), btn_submit.getStatus());

    }

    //删除某一个检测点所有的推荐服务项目view
    private void clearCloneItemServiceItem(AloneNewBean.ItemQuestionListBean itemBean){
        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> questionList1 = itemBean.questionDetectionTempletQuestionList;
        try {
            for (int i = 0; i < questionList1.size(); i++){
                    Iterator<AloneServiceListBean> iterator = serviceList.iterator();
                    while (iterator.hasNext()) {
                        AloneServiceListBean next = iterator.next();
                        if (next.getQuestionBaseId() == questionList1.get(i).questionBaseId) {
                            iterator.remove();
                        }
                    }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 将当前集合中所有含有正确选项的检测题目 设置成pass
     * @param itemBean
     * @param index
     */
    private void setPassBean(AloneNewBean.ItemQuestionListBean itemBean, int index) {
        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> questionList = itemBean.questionDetectionTempletQuestionList;
        if (X3StringUtils.isListEmpty(questionList)) {
            return;
        }
        for (int j = 0; j < questionList.size(); j++) {
            String type = questionList.get(j).type;
            List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> carList = questionList.get(j).questionCarMilesDeductionEntityList;
            switch (type) {
                case AloneContainerStatusDef.CHOICE:
                    int isCanPass = 0;
                    if (X3StringUtils.isListEmpty(carList)) {
                        continue;
                    }
                    String content = "";
                    for (int passIndex = 0; passIndex < carList.size(); passIndex++) {
                        String status = carList.get(passIndex).status;
                        if (AloneSubmitStatus.PASS.equals(status)) {
                            content = carList.get(passIndex).optionDescription;
                            isCanPass++;
                        }
                    }
                    if (isCanPass == 1) {
                        keepAlone(index,j,type,content);
                    }
                    break;
                case AloneContainerStatusDef.PERCENT_SLIDER:
                case AloneContainerStatusDef.NUMBER:
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (layoutUtils.getCv_view() != null && layoutUtils.getCv_view().getParent() != null) {
                layoutUtils.exitCamera();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("检测系统详情页");
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveItemComment();
        MobclickAgent.onPageEnd("检测系统详情页");

    }

    public static class DoubleClickListener implements View.OnClickListener {
        private static final long DOUBLE_TIME = 1000;
        private static long lastClickTime = 0;

        @Override
        public void onClick(View v) {
            long currentTimeMillis = System.currentTimeMillis();
            if (currentTimeMillis - lastClickTime < DOUBLE_TIME) {
                onDoubleClick(v);
            }
            lastClickTime = currentTimeMillis;
        }
        public void onDoubleClick(View v){};
    }

    public static class EditeTagBean{
        public long questionBaseId;
        public String tagName;
    }

}
